Why am I not getting desired values using loop?
1 次查看(过去 30 天)
显示 更早的评论
I have data like
br_peaks =
Columns 1 through 15
0.0002 0.2118 0.4623 0.7067 0.9873 1.2611 1.5412 1.8127 2.0791 2.3712 2.6544 2.9500 3.2134 3.4818 3.7596
Columns 16 through 19
4.0461 4.3143 4.5847 4.8658
I want to make another data in spicific manner. For each value, I will subtract it from three forward points and three backward points and save it in another variable, points(say). I code this using for loops but I am getting only negative points but it should have positive points also.
my code is below. Could anyone help me where did mistake?
br_peaks = [ 0.0002 0.2118 0.4623 0.7067 0.9873 1.2611 1.5412 1.8127 2.0791 2.3712 2.6544 2.9500 3.2134 3.4818 3.7596...
4.0461 4.3143 4.5847 4.8658]
for iii = 1:length(br_peaks)
for jj = 1:length(br_peaks)
if iii<3 && br_peaks(jj)<br_peaks(iii+3)
points(jj) = br_peaks(jj)-br_peaks(iii);
elseif iii+3 > length(br_peaks) && br_peaks(jj)>br_peaks(iii-3)||br_peaks(jj)>br_peaks(iii)
points(jj) = br_peaks(jj)-br_peaks(iii);
elseif iii>=3 && br_peaks(jj)>br_peaks(iii-2) && br_peaks(jj)<br_peaks(iii+3)
points(jj) = br_peaks(jj)-br_peaks(iii);
end
end
end
12 个评论
Torsten
2022-7-19
编辑:Torsten
2022-7-19
[1 2 3 4 5 6 7]
Step 1, subtracting 1 from the three forward points:
[1 1 2 3 5 6 7]
Step 2, subtracting 2 from 1 backward and three forward points:
[-1 2 1 2 3 6 7]
Step 3, subtracting 3 from 2 backwards and three forward points:
[-2 -1 3 1 2 3 7]
...
Step 7, subtracting 7 from 3 backward points:
[1 2 3 -3 -2 -1 7]
Now you have 7 result vectors.
Is it that what you want ?
If not, modify the example accordingly.
采纳的回答
Jeffrey Clark
2022-7-19
lbr = length(br_peaks);
points = nan(lbr,7); % each row is 1->lbr; cols for a row are nan filled
% could change to cells of variable length arrays
for iii = 1:lbr
k = 1;
for jj = max([1,iii-3]):min([iii+3,lbr]) % could rewrite loop to one statement instead
points(iii,k) = br_peaks(jj)-br_peaks(iii);
k = k+1;
end
end % after rewrite of inner loop probably could rewrite to one statement
0 个评论
更多回答(1 个)
Torsten
2022-7-19
br_peaks = [1 2 3 4 5 6 7];
lbr = numel(br_peaks);
points = repmat(br_peaks,lbr,1);
for iii = 1:lbr
for jj = max(1,iii-3):max(0,iii-1)
points(iii,jj) = points(iii,jj) - br_peaks(iii);
end
for jj = max(lbr-2,iii+1):min(lbr,iii+3)
points(iii,jj) = points(iii,jj) - br_peaks(iii);
end
end
points
0 个评论
另请参阅
类别
在 Help Center 和 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!