the loop question for the for loop. k=1:n
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I have a questions for a for loop questions.
this is a matlab code without for loop .
n=0.1;
b1=1;
b2=6;
b3=5;
b4=2;
b5=5;
b6=8;
y1=[1,0,2];
y2=[1,1,2];
y3=[1,2,1];
y4=[-1,3,-1];
y5=[-1,2,1];
y6=[-1,3,2];
a1=[1;0;0];
anew1=a1'+n*(b1-y1*a1)*y1;
anew2=anew1+n*(b2-y2*anew1')*y2;
anew3=anew2+n*(b3-y3*anew2')*y3;
anew4=anew3+n*(b4-y4*anew3')*y4;
anew5=anew4+n*(b5-y5*anew4')*y5;
anew6=anew5+n*(b6-y6*anew5')*y6
anew7=anew6+n*(b1-y1*anew6')*y1;
anew8=anew7+n*(b2-y2*anew7')*y2;
anew9=anew8+n*(b3-y3*anew8')*y3;
anew10=anew9+n*(b4-y4*anew9')*y4;
anew11=anew10+n*(b5-y5*anew10')*y5
anew12=anew11+n*(b6-y6*anew11')*y6
anew13=anew12+n*(b1-y1*anew12')*y1
and i want to use the for loop to make the code shorter and clear,
n=0.1;
b=[1;6;5;2;5;8;1;6;5;2;5;8;1];
y1=[1,0,2];
y2=[1,1,2];
y3=[1,2,1];
y4=[-1,3,-1];
y5=[-1,2,1];
y6=[-1,3,2];
y7=[1,0,2];
y8=[1,1,2];
y9=[1,2,1];
y10=[-1,3,-1];
y11=[-1,2,1];
y12=[-1,3,2];
y13=[1,0,2];
y=[y1;y2;y3;y4;y5;y6;y7;y8;y9;y10;y11;y12;y13];
a1=[1;0;0];
anew=[1,0,0];
for k=1:13
anew=anew+n*(b(k)-y(k,:)*(anew)')*y(k)
end
but i don't know why the two loop answes is different ,it should be same?
0 commentaires
Réponses (1)
Jos (10584)
le 5 Fév 2018
Your code is very unclear. Learn to use arrays and matrices. Rather than
b1 = 2 ; b2 = 4 ; b3 = ...
y1 = [1 2 3] ; y2 = [5 6 7] ; ...
use
b = [2 4 ...] % store b_k as position b(k)
y = [1 2 3 ; 5 6 7 ; ...] % store y_k in row y(k,:)
3 commentaires
Stephen23
le 5 Fév 2018
Modifié(e) : Stephen23
le 5 Fév 2018
"why the answers is different ?"
Because your code is too complex for such a simple task, makes it hard to understand, and hides bugs easily. You should follow Jos' advice and learn to use matrices and arrays instead.
Tip: whenever you write numbered variable names then you are doing something wrong and you should be using an array:
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!