MATLAB Answers

How to use "if statement" for different matrix?

조회 수: 1(최근 30일)
sky walker
sky walker 2021년 7월 14일
댓글: sky walker 2021년 7월 17일
i dont know how to explain my question,
lets say i have 4 matrix
a = [1 3 5; 2 4 7];
b = [1 2 5; 2 4 6];
c = [1 4 5; 4 4 7];
d = [1 3 1; 2 4 1];
i want use like
for i=1:4
if a, b and d then
x=2+n
AK= a*n*x
BK= b*n*x
DK=b*n*x
else (only c)
x=7+n
CK=c*n*x
end
end
kind of like that?
hope you understand. Thanks
  댓글 수: 2
sky walker
sky walker 2021년 7월 14일
yes, i want to exclude c, because c have different step than other

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

답변(1개)

Stephen
Stephen 2021년 7월 14일
편집: Stephen 2021년 7월 14일
The MATLAB approach is to use arrays and indexing, e.g. using one simple cell array:
V = {[1,3,5;2,4,7];[1,2,5;2,4,6];[1,4,5;4,4,7];[1,3,1;2,4,1]};
W = V;
n = 1;
for k = 1:numel(V)
if k<4
x = 2+n;
else
x = 7+n;
end
W{k} = V{k}*n*x;
end
W{:}
ans = 2×3
3 9 15 6 12 21
ans = 2×3
3 6 15 6 12 18
ans = 2×3
3 12 15 12 12 21
ans = 2×3
8 24 8 16 32 8
Or by just using numeric arrays (which is probably what you should be doing, compare how much simpler and more efficient your MATLAB code would be):
A = cat(3,V{:});
U = cat(3,2,2,2,7);
B = A.*n.*(U+n)
B =
B(:,:,1) = 3 9 15 6 12 21 B(:,:,2) = 3 6 15 6 12 18 B(:,:,3) = 3 12 15 12 12 21 B(:,:,4) = 8 24 8 16 32 8
  댓글 수: 5
sky walker
sky walker 2021년 7월 17일
ok thanks for your help stephen

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by