Create a matrix with multiple values at each element and apply a function to all?

조회 수: 1 (최근 30일)
This is for optimization purposes - I have 2 linspaces of parameters, and a 2 parameter function f (random values/function):
Xs = linspace(0, 1000, 1000)
Ys = linspace(0, 10000, 10000)
f = @(x, y) cos(x) + sin(y)
I want to populate a matrix M which has size [length(Xs), length(Ys)], where each element of M is f(x, y) for each x in Xs and y in Ys.
I can do this slowly with a for/parfor loop - how can I use direct vectorisation to achieve this?
Thanks

채택된 답변

Steven Lord
Steven Lord 2020년 4월 9일
If all the binary operations in your f function support implicit expansion (which is the case for your sample f, as plus supports implicit expansion) call it with vectors of different orientations.
Xs = linspace(0, 1000, 1000);
Ys = linspace(0, 10000, 10000);
f = @(x, y) cos(x) + sin(y);
M = f(Xs.', Ys);
Let's ensure M is the correct size.
isequal(size(M), [length(Xs), length(Ys)]) % true
We can spot-check an element or two of M to ensure it's the same as if we'd called your function with scalar inputs.
check = M(457, 9284) - f(Xs(457), Ys(9284)) % 0 difference

추가 답변 (1개)

the cyclist
the cyclist 2020년 4월 9일
Here is one way:
[XXs,YYs] = meshgrid(Xs,Ys);
fxy = f(XXs,YYs);

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by