필터 지우기
필터 지우기

nest loop

조회 수: 7 (최근 30일)
Dominic Lawson
Dominic Lawson 2011년 3월 29일
Hello,
Here is my code:-
clear all
x = 1:3;
y = 1:3;
a = 1:3;
b = 1:3;
for i = 1:3;
for j = 1:3;
a_pred = a(:,i);
b_pred = b(:,j);
y_pred = a_pred + b_pred.* x;
chi2 = (y-y_pred).^2;
end
end
how would I amend the nested loop so that every single combination of a and b values are calculated in y_pred please? i.e. a(1) and b(1) then a(2) and b(1) all the way to a(3) and b(3).
Thanks

채택된 답변

Matt Fig
Matt Fig 2011년 3월 29일
Why do you think all aren't being calculated? Here is a modified version of your code, not changing the mechanics, which shows what you are getting.
a = 1:3;
b = 1:3;
for i = 1:3;
for j = 1:3;
a_pred = a(:,i);
b_pred = b(:,j);
disp([a_pred b_pred])
end
end
.
.
EDIT
.
Here is how to store all the results in chi2:
x = 1:3;
y = 1:3;
a = 1:3;
b = 1:3;
chi2 = zeros(9,3);
cnt = 0;
for i = 1:3;
for j = 1:3;
cnt = cnt + 1;
a_pred = a(:,i);
b_pred = b(:,j);
y_pred = a_pred + b_pred.* x
chi2(cnt,:) = (y-y_pred).^2;
end
end
chi2
And here is a vectorized version, using NPERMUTEK:
IDX = npermutek(1:3,2);
y_pred = bsxfun(@plus,a(IDX(:,1)), bsxfun(@times,b(IDX(:,2)),x.'));
chi2 = bsxfun(@minus,y,y_pred.').^2
Not that it should be faster here...
  댓글 수: 11
Walter Roberson
Walter Roberson 2011년 3월 29일
I found it by using methods(@i)
Walter Roberson
Walter Roberson 2011년 3월 29일
Good question about 'type'. I was not able to find anything that did not indicate 'simple' there. I did find, though, that functions will use an empty file name for methods that do not have a file of their own. For example, functions(@func2str) where which shows func2str as if it is part of a file that does not actually exist.

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

추가 답변 (0개)

카테고리

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