Do not use the for loop to calculate the first number greater than 0 in each line
1 view (last 30 days)
Show older comments
x=randn(10,10)
...
2 Comments
Jan
on 19 Nov 2022
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.
Accepted Answer
Jan
on 19 Nov 2022
Edited: Jan
on 19 Nov 2022
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 Comments
See Also
Categories
Find more on Sources in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!