条件を初めて満たす時の行数を知りたい
21 views (last 30 days)
Show older comments
[1 4 6 7 2 7 8 9; 2 1 0 5 1 0 2 3 ] のような行列があった時、各行において初めて5を越えるのは何列目?という問題に答えられるコードを教えてください。
今回なら(3,4)と返して欲しいです。
0 Comments
Answers (2)
Hernia Baby
on 11 Mar 2022
find で解決できます
ただ今回の例題ですと、5を超えるものは2行目には存在しません
こういったケースも踏まえてcell型でfind関数を適用します
a = [1 4 6 7 2 7 8 9; 2 1 0 5 1 0 2 3 ]
idx = a > 5
for ii = 1:height(a)
b{ii} = find(idx(ii,:),1);
end
b
1 Comment
Hernia Baby
on 11 Mar 2022
ちなみに5以上ならcell型にする必要はありません
各行ごとに該当する列があるからです
先の回答は各行に当てはまる数値がないケースがあるため、cell型を使用しています
a = [1 4 6 7 2 7 8 9; 2 1 0 5 1 0 2 3 ];
idx = a >= 5
for ii = 1:height(a)
b(ii) = find(idx(ii,:),1);
end
b
Atsushi Ueno
on 11 Mar 2022
Edited: Atsushi Ueno
on 11 Mar 2022
a = [1 4 6 7 2 7 8 9; 2 1 0 5 1 0 2 3];
b = (a - a + 1) ./ (a >= 5) .* cumsum(a - a + 1, 2) % 各行において初めて5を越えるのは何列目?
min(b') % 今回なら(3,4)と返して欲しいです:(a > 5)⇒(a >= 5)にしました
2 Comments
Hernia Baby
on 11 Mar 2022
Edited: Hernia Baby
on 11 Mar 2022
(a - a + 1)は行列をつくるためですね。たしかにones(size(a))だと冗長かも…cumsumでナンバリングしてゼロディバイドでInfに飛ばすのは面白いですね
See Also
Categories
Find more on Annotations 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!