Evaluating 2D function on 2D grid without using "for" loops

조회 수: 49 (최근 30일)
Luqman Saleem
Luqman Saleem 2020년 8월 21일
댓글: Sara Boznik 2020년 8월 22일
I have a function f(x,y) and I want to evaluate it on x,y grid. For example,
f = @(x,y) x^2+y^2;
x = 1:10;
y = 1:5;
%one way to do it is using for loops.
for x=1:10
for y=1:5
result(x,y) = f(x,y);
end
end
Is there any way do it without using "for" loops?
  댓글 수: 1
Stephen23
Stephen23 2020년 8월 22일
"Is there any way do it without using "for" loops?"
Why do you want to avoid for loops? Contrary to what some beignners think, (well-written) for loops are not slow.
Is result preallocated before the loops?

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

답변 (1개)

Sara Boznik
Sara Boznik 2020년 8월 21일
f = @(x,y) x.^2+y.^2;
x = 1:10;
y = 1:5;
[X,Y] = meshgrid(x,y);
meshc(X, Y, f(X,Y))
grid on
You can try that.
Best of luck.
  댓글 수: 2
Luqman Saleem
Luqman Saleem 2020년 8월 21일
Actually, the original function is very large and I will have to put (.) in front of all "^" or "*" operators. It also involves matrix multiplication, so, it will just be very messy if I try to put ".". Is there any way to avoid doing it?
Sara Boznik
Sara Boznik 2020년 8월 22일
Sorry, I do not know faster way

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

카테고리

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

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by