Loop over two variables
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
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
il 11 Giu 2017
Modificato: William White
il 11 Giu 2017
dpb
il 11 Giu 2017
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
il 11 Giu 2017
Modificato: William White
il 11 Giu 2017
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
Più risposte (0)
Categorie
Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!