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!