Vectorization of a Value function

I have a function of 3 variables, say A(x,y,z), that I represent as 3D object. (x,y,z are elements of a grid)
Suppose z is also function of x,y, say z(x,y) and I want to evaluate V(x,y) = A(x,y,z(x,y)). (Where z is the relevant index of the grid)
How do I do this? Obviously I can do this easily with a loop, but is there a better answer?
Btw, the way I am doing it now is like this
for i_y=1:Ny
for i_r = 1:Nr
for i_d =1:Nd
for i_w = 1:Nw
V(i_y,i_r,i_d,i_w)= A(i_y,i_r,i_d,i_w, Z(i_y,i_r,i_d,i_w));
end
end
end
end

댓글 수: 2

Julien
Julien 2012년 10월 8일
편집: Julien 2012년 10월 8일
If A=f(x,y,z(x,y)),then in fact A=f(x,y). Can you describe exactly what you want to do ? do you have the expression to calculate? the function that link z and x,y ?
Sergio, you need to look at meshgrid() function. This provides an easy way to get solution to the problem of vectorially calculating A(x,y,Z(x,y)) or in steps as Julien suggests.
[XX,YY] = meshgrid(x,y); %x,y can be 1D vectors here
Now XX,YY correspond to grid points (XX(1),YY(1)) etc.
Once you have meshgrid just directly evaluate your function, and it will have all the values across the X-Y grid.

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

 채택된 답변

Andrei Bobrov
Andrei Bobrov 2012년 10월 8일

1 개 추천

ii = cell(1,4);
[ii{:}] = ndgrid(1:Ny,1:Nr,1:Nd,1:Nw);
v = cellfun(@(x)x(:),ii,'un',0);
V = zeros(size(ii{1}));
V(v{:})= A(v{:}, Z(v{:}));

댓글 수: 2

Thank you for your help. However, unless I am doing something wrong, this is no faster than using the loop! Actually, while I never ran out of memory by solving my problem with the loop, I am not managing to use your method even with very small dimension (i.e. Ny, Nr, Nd, Nw =4).
(??? Maximum variable size allowed by the program is exceeded.)
Any intuition about why this might be the case?
Andrei Bobrov
Andrei Bobrov 2012년 10월 9일
Often, for large arrays, efficient use of cycle for .. end

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Mathematics에 대해 자세히 알아보기

제품

질문:

2012년 10월 8일

Community Treasure Hunt

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

Start Hunting!

Translated by