Do not use the for loop to calculate the first number greater than 0 in each line
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
x=randn(10,10)
...
2 commentaires
Jan
le 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.
Réponse acceptée
Jan
le 19 Nov 2022
Modifié(e) : Jan
le 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 commentaires
Voir également
Catégories
En savoir plus sur Sources dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!