How to navigate a matrix in Matlab?

Asked

Viewed 1,320 times

-1

Good evening! Can anyone help me with this exercise?

"Create a filename filter_matrix. m and save it to your personal account. Type a function name filter_matrix that receives a matrix as an argument and creates a one-dimensional vector that contains the even elements of the matrix. To know the rest of the division between two numbers use a mod function. • Make an implementation using the for and if instructions • Do another implementation that Matlab find function to find a solution that do not use the for and if instructions. • Test function on command line."

1 answer

0

As the description of the problem became a bit confusing, it follows two possibilities of interpretation. Even elements or even lines of the matrix.

%%
%entrada matriz multidimensional
matr = [[1 2 3 4 5];[6 7 8 9 10];[11 12 13 14 15];[16 17 18 19 20]];

%saida matriz unidimensional
out = filtra_matriz(matr)  %retorna os elementos pares de entrada
out = filtra_matriz2(matr) %retorna as linhas pares de entrada da matriz

%%
%segunda parte, usando find
matr2 = 2*matr;    %tirando copia e multiplicando por 2 para monstrar a
                   %diferenca entre posicao e conteudo 
matr2(1:2:end) = 0;%linhas impares = zero
k = find(matr2)    %posicoes pares
matr2(k)'          %conteudos nas posicoes pares em um vertor 
                   %unidimencional de saida

%%
% ------------------ funcoes ------------------------ %
%captura os elementos pares levando em conta a sequencia de entrada da
%matriz.
function [matriz_out] = filtra_matriz(matriz_in)
    [lin,col] = size(matriz_in);
    cont1 = 1;
    cont2 = 1;
    for ii=1:lin
        for jj =1:col
            if mod(cont1,2)==0
                matriz_out(cont2)= matriz_in(ii,jj);
                cont2 = cont2 + 1;
            end
            cont1 = cont1 + 1;
        end   
    end
end

%%
%captura as linhas pares da matriz de entrada
function [matriz_out] = filtra_matriz2(matriz_in)
    [lin,col] = size(matriz_in);
    cont = 1;
    for ii=2:2:lin
        for jj =1:col
                matriz_out(cont)= matriz_in(ii,jj);
                cont = cont + 1;
        end
    end   
end

Browser other questions tagged

You are not signed in. Login or sign up in order to post.