Loop over two variables
显示 更早的评论
I have a formula
U(x,y) = some formula that depends on x and y
x and y are Cartesian coordinates and U is the output that depends on x and y.
I want to create an array U that contains the value of U for many x and y. Usually, I would use meshgrid, but do not want to do this (for particular reasons..).
The domain of x and y is something like x from -x to +x in small definable increments y from -y to +y in small definable increments
So I guess I will have two loops one nested in another?
So it might be y = -y then calculate all values of U for all x and for fixed y = -y
then increase the value of y incrementally and calculate all values of U for all x and y+increment of y
This seems simple, but I am getting confused!
thanks for your help W
5 个评论
dpb
2017-6-11
Well, the end result will be same as if you had used meshgrid so why not?
ic=0;
x=-xL:dx:xH
for y=-yL:dy:yH
U(:,ic)=fnU(x,y);
end
vectorizes over x for each y. NB: fnU must return column vector and you'll want to preallocate before the loop based on length() two X,_Y_ vectors.
William White
2017-6-11
编辑:William White
2017-6-11
dpb
2017-6-11
That means your vectorized function fails, not meshgrid
Can you illustrate the problem in a reasonably short function? Generally there's a way to vectorize even with if
William White
2017-6-11
编辑:William White
2017-6-11
dpb
2017-6-11
"If a>0 and b<-1 then T = ... So using the meshgrid a and b are arrays rather than single values."
Sure. But logical addressing can solve that dilemma...
isAB=(a>0 & b<-1); % logical array of condition
T( isAB)=whatever(x(isAB),y(isAB),Q,R,S,...); % compute those
T(~isAB)=thealternate(x(~isAB),y(~isAB),Q,R,S,...); % the rest
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 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!