Return only odd items

This is my first attempt at learning Matlab and I am trying to do my homework which is evaluated by a p file. I think my function is correct, but I keep getting negative feedback from automatic feedback that evaluates the function

(Feedback: your function made a mistake for argument (s) [1 2 3; 4 5 6; 7 8 9])

Problem:

Write a function odd_index that takes a matrix, M, as an input argument and returns a matrix containing only those elements from M that are odd rows and columns. In other words, it would return the elements of M at indices (1,1), (1,3), (1,5), ..., (3,1), (3,3), (3,5), ... etc. Note that both the row and column of the item must be odd to be included in the output. The following are not returned: (1,2), (2,1), (2,2) because either a row or a column or both are even. As an example, if M was a 5-by-8 matrix then the output should be 3-to-4 because the function omits rows 2 and 4 from M, and also skips columns 2, 4, 6, and 8 from M.

This is the function I wrote:

function odd_index
M=[1:5; 6:10; 11:15; 16:20; 21:25];
M=M(1:2:end, 1:2:end);
M
end

      

Any suggestion on what I am doing wrong would be appreciated.

+3


source to share


2 answers


Your function should take a matrix as an input argument M

:

function M_out = odd_index(M)
    M_out = M(1:2:end, 1:2:end);
end

      



So the "p file" can test it for different inputs.

+2


source


function matA=odd_index(matB)
[r,c]=size(matB);
matA=matB(1:2:r,1:2:c);
end

      



0


source







All Articles