필터 지우기
필터 지우기

How can I return the values of a loop

조회 수: 6 (최근 30일)
zaxtronix
zaxtronix 2016년 5월 12일
댓글: Andrei Bobrov 2016년 5월 13일
I want to return the entire values of k matrice but I only end up with values from the last row.
for i = 1:5,
j = 0:i;
k = i.^2 + i*j + j.^2
end

채택된 답변

Felix Lauwaert
Felix Lauwaert 2016년 5월 12일
편집: Felix Lauwaert 2016년 5월 12일
You are computing k once for each value of i and overwriting it. If I understand what you want, try:
i = 1:5;
j = 0:5;
k = zeros(numel(i),numel(j));
for a = 1:numel(i)
for b = 1:numel(j)
k(a,b) = i(a)^2 + i(a)*j(b) + j(b)^2;
end
end
display(k)
  댓글 수: 1
zaxtronix
zaxtronix 2016년 5월 13일
Thanks a lot man, how did you do it using this numel function, I definitely wouldn't have been able to come about it.

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

추가 답변 (1개)

Andrei Bobrov
Andrei Bobrov 2016년 5월 12일
편집: Andrei Bobrov 2016년 5월 12일
n = 5;
k = tril(((1:n)'*ones(1,n+1)).^2+(1:n)'*(0:n)+(ones(n,1)*(0:n)).^2,1);
with for..end loop
n = 5;
k = zeros(n,n+1);
for ii = 1:5,
jj = 0:ii;
k(ii,1:ii+1) = ii.^2 + ii*jj + jj.^2;
end
  댓글 수: 2
zaxtronix
zaxtronix 2016년 5월 13일
thanks, this also works perfectly, except doing an extraction will require one dealing with zeros in the array
Andrei Bobrov
Andrei Bobrov 2016년 5월 13일
hm...
[ii,jj] = ndgrid(1:5,0:5);
k = ii.^2 + ii.*jj + jj.^2;

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

카테고리

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