Loop over two variables
15 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
dpb
il 11 Giu 2017
"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
Risposta accettata
Geoff Hayes
il 11 Giu 2017
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 Commenti
dpb
il 11 Giu 2017
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...
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Logical in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!