For loop with if statement!

1 view (last 30 days)
Sophia
Sophia on 27 Sep 2019
Answered: the cyclist on 27 Sep 2019
Here is the samplf of what i am trying to do-
clear all;
clc;
s = [1 2 3; 4 0.5 1; 1.3 2 1; 1.5 1.6 2.8]
a(1,:,:) = [ 1 2 3 ; 4 5 6; 7 8 9;10 11 12]
a(2,:,:) = [ 11 12 13 ; 14 15 16; 17 18 19;110 111 112]
a(3,:,:) = [ 111 112 113 ; 114 115 116; 117 118 119;1110 1111 1112]
dd= []
for i = 1:size(a,1)
for j = 1:size(a,2)
for k = 1:size(a,3)
if s(j,k)>1.5
dd(:,:) = double(a(:,j,k));
else
end
end
end
end
%Expected Answer dd = [2 3 4 8 11 12; 12 13 14 18 111 112;112 113 114 118 1111 1112];
Can anyone tell me how to get the expected answer, i created this sample to understand the problem with some simplicity.
  1 Comment
Ahmed Zankoor
Ahmed Zankoor on 27 Sep 2019
Firstly, you get an assignment error for matrix a. But it works if you initialize the matrix
a = zeros(3,4,3);
a(1,:,:) = [ 1 2 3 ; 4 5 6; 7 8 9;10 11 12]
a(2,:,:) = [ 11 12 13 ; 14 15 16; 17 18 19;110 111 112]
a(3,:,:) = [ 111 112 113 ; 114 115 116; 117 118 119;1110 1111 1112]
The second part is not clear at all.
  • a(:,j,k) is a 3*1 vector, so you can not form dd like your expected answer.
  • dd should be initialized so that you can assign different values at differnt positions.

Sign in to comment.

Answers (1)

the cyclist
the cyclist on 27 Sep 2019
It does not give the expected answer, but using
dd = [dd double(a(:,j,k))];
instead of
dd(:,:) = double(a(:,j,k));
is a step toward what you are expecting, and maybe is enough for you to figure it out?
Also, MATLAB numeric variables are type double by default, so you could just do
dd = [dd a(:,j,k)];
to get the same result.

Community Treasure Hunt

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

Start Hunting!