nested for loop

I was wondering if there was a way to write nested loops so they are more efficient. For example:
for a = 1:1:100
for b = .5:.1:3
x = bestfitfun(a,b);
end
end
the bestfitfun is a function that runs if statements and really isn't a bottleneck. Any suggestions would be greatly appreciated.
Thank you!

댓글 수: 1

per isakson
per isakson 2012년 4월 16일
in the signature of bestfit are a and b assumed to be scalars?

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

답변 (1개)

Pavel Gorodetsky
Pavel Gorodetsky 2012년 6월 15일

1 개 추천

if nesting is an issue, you can use one loop only:
a = 1:1:1000;
b = .5:.1:3;
N = length(a)*length(b);
[A,B] = meshgrid(a,b);
for ii = 1:N
x = bestfitfun(A(ii),B(ii));
end
of course, as per isakson implies, if your bestfitfun could take vectors as an input, and work in some vectorized form, you could loose the two loops altogether:
a = 1:1:1000;
b = .5:.1:3;
x = bestfitfun(a,b);

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2012년 4월 16일

Community Treasure Hunt

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

Start Hunting!

Translated by