I am trying to implement this double loop. There is lot of material online on double looping in matlab but I don't manage to make it work.
This is my code:
debt = nan(49,1)
for j = -(6:12)
for i = 2:8
debt(j, i) = ((1 + 0.93) - (1 + j)) + 134.77 + (i - 3.3)
end
end
I would like to be able to save debt as a 49x1 vector.
What's wrong with my loop?
Thanks

 채택된 답변

Andrei Bobrov
Andrei Bobrov 2020년 4월 8일
편집: Andrei Bobrov 2020년 4월 8일

0 개 추천

Just:
ii = 2:8;
jj = -(6:12);
debt = 132.4 - jj(:) + ii(:)';
debt = debt(:);
or with for-loop:
ii = 2:8;
jj = -(6:12);
debt = nan(7);
for j = 1:7
for i = 1:7
debt(j, i) = 132.4 - jj(j) + ii(i);
end
end

댓글 수: 4

Armando MAROZZI
Armando MAROZZI 2020년 4월 8일
If I run that code I get again just the last value stored in debt. It doesn't create a 49x1 vector, does it?
Armando MAROZZI
Armando MAROZZI 2020년 4월 8일
Andrei, I guess I explained myself not clearly in the question. With your codes I get a 7x7 matrix. I need to be stored as a 49x1 vector. What to put in deb(?,?) in this case? Thanks a lot
Andrei Bobrov
Andrei Bobrov 2020년 4월 8일
편집: Andrei Bobrov 2020년 4월 8일
Variant:
ii = 2:8;
jj = -(6:12);
[j,i] = ndgrid(jj,ii);
debt = 132.4 - j(:) + i(:);
other
n = 7;
ii = (2:8)';
jj = -(6:12)';
debt = 132.4 - jj(kron((1:n)',ones(n,1))) + ii(kron(ones(n,1),(1:n)'));
Armando MAROZZI
Armando MAROZZI 2020년 4월 8일
great! Thanks a lot!

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

추가 답변 (0개)

카테고리

도움말 센터File 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