how to write if statement for matrix ?

42 次查看(过去 30 天)
how to write if statement for matrix ?
in other words:
test= [5;6;0;-1;0]
this is the condition:
if test==0
disp 0
else
disp 5
end
and I want to give answer for each row (for 5 and 6 and 0 ....etc)

回答(1 个)

Geoff Hayes
Geoff Hayes 2020-5-16
Ibrahim - what are you trying to do here? Just display (with disp) a message depending upon whether an element is a zero or not? The simplest and least efficient way to do this is with a loop
test = [5;6;0;-1;0];
for k = length(test)
if test(k) == 0
disp 0;
else
disp 5;
end
end
I don't think that is what you really want though so you may need to provide more details. I also suspect that you shouldn't need to use a for loop and that may be the case depending upon the details you provide.
  2 个评论
Ibrahim AlZoubi
Ibrahim AlZoubi 2020-5-17
I have two matrices first one is:
test = [5;6;0;-1;0;5;0;6;0;8];
and the second one is:
test5 = [2;6;8;-1;0;7;8;6;8;8];
how to generate third matrix which is the result after the condition (if statment)...
the condition is if the value of test is equal 0 then the value of the new matrix is 0 , else if the value of the first matrix isn't equal 0 do some calculations on the second matrix which is test5 like (test5*7+5).
so the third matrix values depends on the two matrix before...
Geoff Hayes
Geoff Hayes 2020-5-18
Is the output array of the same dimensions as test?
test = [5;6;0;-1;0];
outputArray = size(test);
for k = length(test)
if test(k) == 0
outputArray(k) = 0;
else
% do a calculation of some kind
outputArray(k) = 42; % <--- your code here
end
end

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by