Using a while loop on each column in an array?
조회 수: 3 (최근 30일)
이전 댓글 표시
Hi all,
I have a script that performs an action on each column of an array at once. I would like to set up a loop where I do this multiple times. Each time I will be taking the mean of each column and comparing it to another value. I would like to know at which iteration each column's mean reaches that value, although each column will do this at different times. With each iteration the columns will get 1 longer, thus making the mean more accurate.
I don't want my script to stop when only one of the columns reaches this point, but I also don't want it to stop and only record the iteration when all of them have reached this value.
For instance:
B = 4;
for i = 1:4
if i == 1
A = [1,2,3;1,2,3;1,2,3;4,4,4];
elseif i == 2
A = [1,2,3;1,2,3;1,2,3;4,4,4;4,4,4];
elseif i == 3
A = [1,2,3;1,2,3;1,2,3;4,4,4;4,4,4;4,4,4];
elseif i == 4
A = [1,2,3;1,2,3;1,2,3;4,4,4;4,4,4;4,4,4;4,4,4];
end
j = mean(A)/B;
end
If I want j > .65, I would like a vector that tells me column one reached this at i == 4, column 2 reached this at i == 2 and column 3 reached this at i == 1. If I didn't use a while loop I do have a fixed number of iterations I could do, I would just like to avoid doing them all if I can help it. But maybe I could do that and then go back with cumsum? Any help would be appreciated, thank you!
댓글 수: 2
CS Researcher
2016년 5월 5일
First of all mean(A)/B will be a vector and not a scalar value. Also, I am not sure I completely understood your problem. Can you elaborate your example further?
답변 (1개)
Guillaume
2016년 5월 5일
I'm not entirely clear on everything particularly on the stop condition for your loop.
You can indeed calculate the result a posteriori:
A = [1,2,3;1,2,3;1,2,3;4,4,4;4,4,4;4,4,4;4,4,4];
cummean = bsxfun(@rdivide, cumsum(A), (1:size(A, 1))');
%we can use max to find the first row of each column above a threshold or use a loop
[~, firstrow] = max(cummean / 4 > 0.65, [], 1)
firstrow = firstrow - 4
If you want to do the tracking in the loop, it's also trivial to do:
fullA = [1,2,3;1,2,3;1,2,3;4,4,4;4,4,4;4,4,4;4,4,4];
firstrow = zeros(1, size(A, 2));
for iter = 1 : size(fullA, 1)
A = fullA(1:iter, :);
abovethreshold = mean(A) / 4 > 0.65;
firstrow(abovethreshold & ~firstrow) = iter;
if all(firstrow)
break; %is this your stop condition?
end
end
댓글 수: 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!