loop questions for k=1:n
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
I have a add loop questions
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
how can I change this type of questions for a loop question ?
2 Kommentare
Stephen23
am 5 Feb. 2018
Numbered variable names are how beginners force themselves into writing slow, buggy, complex code:
If you put your data into arrays then you could neatly and efficiently access that data in a loop using indexing.
Antworten (1)
Jan
am 5 Feb. 2018
Bearbeitet: Jan
am 5 Feb. 2018
This was answered in your other thread already: Replace a list of variables with an index hidden in the names by an array.
Maybe something like this:
b = rand(1, 6);
y = rand(1, 6);
index = [1:6, 1:6, 1];
a = 0; % Or however this is initialized
for k = index
a = a + n * (b(k) - y(k) * a) * y(k);
end
The transpose operator in your code seems like some inputs are vectors. Then use e.g. y(:, k) instead of y(k).
This method is more compact, easier to read and to debug and expected to be faster. The rule is easy: Never hide indices in the names of variables.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!