Vectorization of a Value function
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
Muthu Annamalai
2012-10-8
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
2012-10-8
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!