MATLAB Answers

How to use "if statement" for different matrix?

1 view (last 30 days)
sky walker
sky walker on 14 Jul 2021
Commented: sky walker on 17 Jul 2021
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 Comments
sky walker
sky walker on 14 Jul 2021
yes, i want to exclude c, because c have different step than other

Sign in to comment.

Answers (1)

Stephen
Stephen on 14 Jul 2021
Edited: Stephen on 14 Jul 2021
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 Comments

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!