Printing positive numbers backwards

조회 수: 1 (최근 30일)
David Tejcek
David Tejcek 2019년 7월 2일
편집: Stephen23 2019년 7월 16일
Hi all,
I was just wondering if anyone could help me out with some code to go through a matrix of numbers and find the positive numbers and print only them (remove the negative numbers) in a new array but also print them in reverse order,
Thanks a lot!
  댓글 수: 1
Stephen23
Stephen23 2019년 7월 2일
편집: Stephen23 2019년 7월 2일
Please show us what you have tried so far.
You would have made significant progress on this by doing the introductory tutorials:

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

답변 (1개)

Rajani Mishra
Rajani Mishra 2019년 7월 16일
Hi,
I understand that you want to extract positive numbers from matrix and store them in a new array and then traverse the new array in reverse order.
Refer this code:
[row,col] = size(mt)
arr = [];
for i = 1:row
for j = 1:col
if mt(i,j) > 0
arr(numel(arr) + 1) = mt(i,j);
end
end
end
for i = numel(arr):-1:1
disp(arr(i));
end
  댓글 수: 1
Stephen23
Stephen23 2019년 7월 16일
편집: Stephen23 2019년 7월 16일
Is there are reason why this answer does not use MATLAB's basic (and most useful) features, e.g. logical indexing, code vectorization, etc.?
Note that the output array should be preallocated:
It is much simpler to just use efficient logical indexing (this gives the same output):
B = mt.';
flipud(B(B>0))

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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by