How to loop through a matrix, one row at a time using a for loop and conditions

189 ビュー (過去 30 日間)
hanion20
hanion20 2018 年 11 月 23 日
コメント済み: DEBORAH 2024 年 10 月 16 日
So I have a 4x2 matrix
Matrix = [20,5; 30, -6; 40,8; 50,10];
. And I want to create a for loop with if-else statement that goes through the matrix and test if either the row or col value is negative, then it would display something like 'neg'. If both values are positive, then there will be a function called; (lets say the function is called Func).
how do I go through and test each row and col value to see if it is neg or pos?
thanks

採用された回答

madhan ravi
madhan ravi 2018 年 11 月 23 日
編集済み: madhan ravi 2018 年 11 月 23 日
Read about logical indexing:
Matrix = [20,5; 30, -6; 40,8; 50,10];
for i = 1:size(Matrix,1)
if Matrix(i,1)<0 || Matrix(i,2)<0
disp('neg')
elseif Matrix(i,1)>0 && Matrix(i,2)>0
% some function
end
end

その他の回答 (1 件)

Stephen23
Stephen23 2018 年 11 月 23 日
編集済み: Stephen23 2018 年 11 月 23 日
Simpler:
M = [20,5;30,-6;40,8;50,10]
X = all(M>=0,2)
for k = 1:size(M,1)
if X(k)
M(k,:)
end
end

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by