Why this simple for loop doesn't work?
18 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Fatemeh Sharafi
le 12 Juil 2021
Modifié(e) : Stephen23
le 12 Juil 2021
I have a for loop and I want it to calculate the mean of sum of square of elements of an array, in a fixed-length period;
The array is b (1 by 30). the segments that I want to calculate the mean(sum(square(b))) are 3 by 3 steps: for example first calculate it for the first 3 elements. then calculate for the second three elements, and so forth.
Now the problem is this loop doesn't work for all i and j values. it only calculates for the last i an last j.
Please guide me with this. thanks in advance
here's the code:
b=[31,12,14,8,32,38,45,29,39,4,44,6,21,29,19,26,2,36,42,47,3,47,6,26,44,26,5,43,22,36];
R1405_bar=zeros(1,10);
for i=1:1:10
for j=3:3:30
R1405_bar(1,i)=(sum(b(j-2:j).^2));
end
end
2 commentaires
Stephen23
le 12 Juil 2021
Modifié(e) : Stephen23
le 12 Juil 2021
b = [31,12,14,8,32,38,45,29,39,4,44,6,21,29,19,26,2,36,42,47,3,47,6,26,44,26,5,43,22,36];
The simple MATLAB approach:
R1405_bar = sum(reshape(b,3,[]).^2)
Vs. the complex approach:
R1405_bar = zeros(1,10);
j = 1;
for i=1:3:30
R1405_bar(j)=(sum(b(i:i+2).^2));
j = j + 1;
end
R1405_bar
Réponse acceptée
Aakash Deep Chhonkar
le 12 Juil 2021
The issue is in your nested for loop. For every iteration of i, you are computing the same set of commands hence, the output is same everything. Your nested for loop index j should depend on the outer for loop index i.
As far as I understand the problem statement, there is no need of the nested loop. You can compute the mean of sum of squares of elements of array using single loop. Refer below code,
b=[31,12,14,8,32,38,45,29,39,4,44,6,21,29,19,26,2,36,42,47,3,47,6,26,44,26,5,43,22,36];
R1405_bar=zeros(1,10);
j = 1;
for i=1:3:30
R1405_bar(j)=(sum(b(i:i+2).^2));
j = j + 1;
end
0 commentaires
Plus de réponses (3)
Simon Chan
le 12 Juil 2021
For each i, the value on R1405_bar is keep overwrite as j runs from 3 to 30.
On the other hand, you just calculate sum of square of element only, missing the mean.
0 commentaires
Jogesh Kumar Mukala
le 12 Juil 2021
Hi,
Assuming you want to find the mean of squares of consecutive three elements of 'b' array and store in R1405_bar, the issue with your code is the 'j' loop is running completely for every 'i' and it is storing the same result( i.e end result of 'j' loop) in every element of R1405_bar. You may find the below code which may solve the issue.
b=[31,12,14,8,32,38,45,29,39,4,44,6,21,29,19,26,2,36,42,47,3,47,6,26,44,26,5,43,22,36];
R1405_bar=zeros(1,10);
j=[3:3:30]
for i=1:1:10
R1405_bar(1,i)=(sumsqr(b(j(i)-2:j(i))))/3;
end
0 commentaires
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!