For loop with if statement!

1 次查看(过去 30 天)
Sophia
Sophia 2019-9-27
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 个评论
Ahmed Zankoor
Ahmed Zankoor 2019-9-27
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.

请先登录,再进行评论。

回答(1 个)

the cyclist
the cyclist 2019-9-27
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.

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by