double for loop with changing start point at second loop. need help, wrong output.

1 view (last 30 days)
i have simplified my matlab script to this:
clear all
clear variables
clc
n = 10
for N1 = 1:1:(n-1)
C = N1;
for N2 = (N1+1):1:n
D = N2;
F = C+D;
X1(:,N2) = F;
end
X2 = X1.';
X3(:,N1) =X2;
end
X3
Results are:
X3 =
0 0 0 0 0 0 0 0 0
3 3 3 3 3 3 3 3 3
4 5 5 5 5 5 5 5 5
5 6 7 7 7 7 7 7 7
6 7 8 9 9 9 9 9 9
7 8 9 10 11 11 11 11 11
8 9 10 11 12 13 13 13 13
9 10 11 12 13 14 15 15 15
10 11 12 13 14 15 16 17 17
11 12 13 14 15 16 17 18 19
so the problem here is that the output of matrix X3 is wrong. the reason why it is wrong is because of the second for loop. when the start point changes of the second for loop it should have a 0 value for all the points before the start point. but in this script when N1=5 and N2 = 6 to 10 we obtain an output for N2 = 2-5 also from the previously values. The second for loop do not reset values for each loop. how do i fix this?? the results should be like this matrix:
X3 =
0 0 0 0 0 0 0 0 0
3 0 0 0 0 0 0 0 0
4 5 0 0 0 0 0 0 0
5 6 7 0 0 0 0 0 0
6 7 8 9 0 0 0 0 0
7 8 9 10 11 0 0 0 0
8 9 10 11 12 13 0 0 0
9 10 11 12 13 14 15 0 0
10 11 12 13 14 15 16 17 0
11 12 13 14 15 16 17 18 19

Accepted Answer

Nobel Mondal
Nobel Mondal on 13 May 2015
n = 10;
result = zeros(n,n-1);
for N1=1:1:(n-1)
for N2=(N1+1):1:n
result(N2,N1) = N2+N1;
end
end

More Answers (1)

Stephen23
Stephen23 on 13 May 2015
Edited: Guillaume on 13 May 2015
It is much simpler and neater with hankel and tril, no loops are required:
>> tril(hankel([0,3:11],11:19),-1)
ans =
0 0 0 0 0 0 0 0 0
3 0 0 0 0 0 0 0 0
4 5 0 0 0 0 0 0 0
5 6 7 0 0 0 0 0 0
6 7 8 9 0 0 0 0 0
7 8 9 10 11 0 0 0 0
8 9 10 11 12 13 0 0 0
9 10 11 12 13 14 15 0 0
10 11 12 13 14 15 16 17 0
11 12 13 14 15 16 17 18 19
It is worth learning how to vectorize code in MATLAB. And to use the inbuilt functions, which are almost always going to be faster and neater than solving everything with nested loops.
edit by guillaume: changed name of function and link to hankel (was hadamard), the code showed the right function.
  1 Comment
Nobel Mondal
Nobel Mondal on 13 May 2015
Thanks Stephen. I completely agree with you. I need to learn more inbuilt matrix operations.
Just to generalize the code a bit:
>> n=10;
>> result = tril(hankel([0,3:n+1],(n+1):(2*n-1)),-1);

Sign in to comment.

Categories

Find more on Loops and Conditional Statements 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!