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

49 views (last 30 days)
Luqman Saleem on 21 Aug 2020
Commented: Sara Boznik on 22 Aug 2020
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?
Stephen23 on 22 Aug 2020
"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?

Sara Boznik on 21 Aug 2020
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.
Sara Boznik on 22 Aug 2020
Sorry, I do not know faster way

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by