Loop over two variables
9 次查看(过去 30 天)
显示 更早的评论
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
"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
采纳的回答
Geoff Hayes
2017-6-11
William - you could do something like the following if you assume that you know your domains for x and y.
numElementsX = length(x);
numElementsY = length(y);
U = zeros(numElementsX, numElementsY);
for r=1:numElementsX
for s=1:numElementsY
U(r,s) = func(x(r),y(s)); % func is just some function that you have defined
end
end
So like you thought, we can use two loops to iterate over all elements contained in the x array and those in the y array. On each iteration of the outer loop, we fix the value of x to be x(r) and then iterate over each element in the y array. And then repeat for the next value of x.
2 个评论
dpb
2017-6-11
I'm still not convinced you can't use meshgrid (with some rework of your function, of course), but for those kinds of numbers use linspace
x=linspace(xLo,xHi,1000); % ditto for y
then as above iterate over x,_y_
The alternative as shown above still works as well altho again you would need to vectorize fnU(x,y) to make use of it.
BTW, it'll probably run noticeably faster if you switch order of for loops and iterate over r first; that is sequential memory storage order in Matlab. 1000x1000 is small enough may not make much difference, but...
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!