Indexing problems using for loop and if statements
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I'm trying to solve a large system of ODE's using ode45. I need to assign y(*negative number) = 0 in the function. This is impossible to avoid because I'm using a loop.
My code is:
k=5
for p =1:21
n=p-11;
shift = k-n;
nshift= n-k;
if shift <1 || shift >length
y(shift) = 0;
if nshift <1 || nshift >length
y(nshift) = 0;
dydt(p) = term1*y(p)*(n-k)^2; + term2*sin((n-k)^2*theta)*
(y(11)*conj(y(shift)) + conj(y(11))*y(nshift))*y(k+11);
end
end
end
I'm having problems with the y(shift) = 0 when shift is negative. How do I fix this?
1 commentaire
Jan
le 21 Nov 2017
Your code is easier to read if you apply the standard code indentation (Ctrl-A Ctrl-I) in the editor. Please remove the typo in the line "dydt(p) = ...": I assume the ";" is not wanted.
Réponses (1)
Jan
le 21 Nov 2017
Does this appear in the function to be integrated? Then it is not smooth and in consequence ODE45 cannot integrate it reliably. See http://www.mathworks.com/matlabcentral/answers/59582#answer_72047.
What is "length"?
You forgot to explain, what "y" is. If you are calculating "dydt", it might be the value to be integrated. But then indexing it is meaningless, because it is continuous.
If "y" is something else, what about:
if shift <1 || shift >length
y_shift = 0;
else
y_shift = y(shift);
end
if nshift <1 || nshift >length
y_nshift = 0;
else
y_nshift = y(nshift);
end
2 commentaires
Jan
le 21 Nov 2017
@matlabkid602: Yes, this is clearer now. One problem remains:
dydt(p) = term1*y(p)*(n-k)^2; + term2*sin((n-k)^2*theta) ...
% Orphand semicolon: ^
And
end %end for loop
end %end if statement
end %end if statement
contains confusing comments: The end close the nearest IF or FOR. Then the FOR loop is closed at the bottom.
Redefining important Matlab functions by local variables causes troubles frequently. Avoid using "length" as a name.
Maybe you want to reorder the IF statements:
for p = 1:length
n = p-11;
shift = k-n; %Positive shift
nshift= n-k; %Negative shift
if shift <1 || shift >length
y_shift = 0;
else
y_shift = y(shift);
end
if nshift <1 || nshift >length
y_nshift = 0;
else
y_nshift = y(nshift);
end
dydt(p) = term1*y(p)*(n-k)^2 + term2*sin((n-k)^2*theta)* ...
(y(11)*conj(y_shift) + conj(y(11))*y_nshift)*y(k+11);
end %end for loop
Do I understand correctly, that "y(shift)" means to access a different component of the current y vector?
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!