How to skip some values in for loop ?
10 views (last 30 days)
Show older comments
mustafa ozendi
on 9 Jan 2019
Commented: mustafa ozendi
on 10 Jan 2019
Dear All,
I am triyng to fill the I_dd array using the array called B_matrix. I initialize the first values of the I_dd array as 1 and then I use this value incrementally to fill following elements of the I_dd . Some elements of my B_matrix array are equal to zero and I want to just skip them. My B_matrix array is:
B(:,:,1) = [3 1 1
1 0 0
1 0 1]
B(:,:,2) = [0 0 0
0 0 1
0 1 2]
B(:,:,3) = [0 0 0
0 0 0
0 0 0]
My code is shown below:
I_dd = zeros(3,3,3);
for k = 1:3
for i = 1:3
for j = 1:3
if i==1 && j==1 && k == 1
I_dd(i,j,k) = 1;
elseif j>1
I_dd(i,j,k) = I_dd(i,j-1,k) + B_matrix(i,j-1,k);
elseif i>1
I_dd(i,j,k) = I_dd(i-1,3,k) + B_matrix(i-1,3,k);
else
I_dd(i,j,k) = I_dd(3,3,k-1) + B_matrix(3,3,k-1);
end
end
end
end
The resulting I_dd array is shown below:
I_dd(:,:,1) = [1 4 5
6 7 7
7 8 8]
I_dd(:,:,2) = [9 9 9
9 9 9
10 10 11]
I_dd(:,:,3) = [13 13 13
13 13 13
13 13 13]
However, the correct I_dd should be:
I_dd(:,:,1) = [1 4 5
6 0 0
7 0 8]
I_dd(:,:,2) = [0 0 0
0 0 9
0 10 11]
I_dd(:,:,3) = [0 0 0
0 0 0
0 0 0]
The problem is due to zeros in the B_matrix. I tried to use continue command but it did not work. ould you please help me about fixing this issue?
I am looking forward to hearing from you
1 Comment
Stephen23
on 9 Jan 2019
Edited: Stephen23
on 9 Jan 2019
@mustafa ozendi: remember to accept my answer (the one where you got that code from):
You have taken my code and are using it, but have not accepted my answer where you got that code from. Accepting answers shows that you value the help of the volunteers who help you.
Accepted Answer
Stephen23
on 9 Jan 2019
Edited: Stephen23
on 9 Jan 2019
Just add this line after those loops:
I_dd(B==0) = 0
to get this:
I_dd(:,:,1) =
1 4 5
6 0 0
7 0 8
I_dd(:,:,2) =
0 0 0
0 0 9
0 10 11
I_dd(:,:,3) =
0 0 0
0 0 0
0 0 0
Note that it is not really possible to do this inside the loops (as you tried) because later loop iterations depend on the values calculated during earlier loop iterations, which means that it is simpler to calculate all values of all loop iterations. But that simple line of code I showed you will give you exactly what you requested, after the loops have finished.
More Answers (0)
See Also
Categories
Find more on Performance and Memory in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!