I have a column matrix with numbers a=[0 1 2 3 4 5] and I want to get matrix b=[0 0 2 2 4 4] Basically all the number should be displayed as their closest even number. Please help me with the logic. It is a column matrix ,I am not sure how to show it in the question as it only shows up as a row matrix
The numbers shown is just an example and the numbers on the matrix a could be random as well. but the solution to matrix b should be the nearest even number, that wouldnt change

 채택된 답변

Mischa Kim
Mischa Kim 2014년 6월 13일
편집: Mischa Kim 2014년 6월 13일

0 개 추천

Manoj, you could use
a = 0:5;
b = a - mod(a,2);
Note, your vector is a row vector. Use the prime operator to turn it into a column vector. Also, I believe by closest you mean lower closest, correct? E.g., 1 is right in between 0 and 2.

댓글 수: 4

Manoj
Manoj 2014년 6월 13일
Thank you so much , that is exactly what I was looking for
BR M
Manoj
Manoj 2014년 6월 13일
I was wondering could this be done with an if statement also ? I tried but i get one single answer but I want answers for each column. Do you have any suggestions?
Sure. There are many ways of doing this, here is one:
a = 0:5;
b = zeros(size(a));
for ii = 1:numel(a)
if ~mod(a(ii),2)
b(ii) = a(ii);
else
b(ii) = a(ii) - 1;
end
end
Manoj
Manoj 2014년 6월 13일
Thank you once again , this is really helpful
BR M

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

질문:

2014년 6월 13일

댓글:

2014년 6월 13일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by