필터 지우기
필터 지우기

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

조회 수: 1 (최근 30일)
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

채택된 답변

Nobel Mondal
Nobel Mondal 2015년 5월 13일
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

추가 답변 (1개)

Stephen23
Stephen23 2015년 5월 13일
편집: Guillaume 2015년 5월 13일
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
Nobel Mondal
Nobel Mondal 2015년 5월 13일
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);

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by