Do not use the for loop to calculate the first number greater than 0 in each line
조회 수: 1 (최근 30일)
이전 댓글 표시
x=randn(10,10)
...
댓글 수: 2
Jan
2022년 11월 19일
This sounds like a homework question. So please show, what you have tried so far and ask a specific question about Matlab. The forum will not solve your homework, but assist you in case of questions concerning Matlab.
채택된 답변
Jan
2022년 11월 19일
편집: Jan
2022년 11월 19일
x = randn(10, 10)
y = x.'; % Required for the last step y(y3==1)
y1 = y > 0
y2 = cumsum(y1)
% Now a row can contain multiple 1's. Another CUMSUM helps:
y3 = cumsum(y2)
y(y3 == 1)
Another way:
x = randn(10, 10)
m = x > 0
y = cumsum(x .* m, 2)
y(~m) = Inf % Mask leading zeros
min(y, [], 2)
Or with beeing nitpicking for the formulation "no for loop":
result = zeros(1, 10);
m = x > 0;
k = 1;
while k <= 10
row = x(k, :);
result(k) = row(find(row(m(k, :)), 1));
k = k + 1;
end
And another method:
[row, col] = find(x > 0);
first = splitapply(@min, col, row);
x(sub2ind(size(x), 1:10, first.'))
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Sources에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!