Why this simple for loop doesn't work?
古いコメントを表示
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 件のコメント
Fatemeh Sharafi
2021 年 7 月 12 日
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
採用された回答
その他の回答 (3 件)
Yongjian Feng
2021 年 7 月 12 日
0 投票
Use a debugger to check why.
Simon Chan
2021 年 7 月 12 日
0 投票
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.
Jogesh Kumar Mukala
2021 年 7 月 12 日
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
カテゴリ
ヘルプ センター および File Exchange で Loops and Conditional Statements についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!