Which part is incorrect?

1 回表示 (過去 30 日間)
Ryan W
Ryan W 2022 年 10 月 15 日
回答済み: Hiro Yoshino 2022 年 10 月 15 日
function [indices] = kWeakestRows(mat,k)% function
disp("The number of soldiers in each row is:")
answer = [];
for i = 1:length(mat)
fprintf("- Row %d: %d\n",i,sum(mat(i,:)));
answer(end + 1,:) = [sum(mat(i,:)),i];
end
answer = sortrows(answer,1);
indices = [];
for i = 1:k
indices(end + 1) = answer(i,2);
end
fprintf("The rows ordered from weakest to strongest are ");
disp(indices);
end
  1 件のコメント
Ghazwan
Ghazwan 2022 年 10 月 15 日
can you explain more?

サインインしてコメントする。

回答 (1 件)

Hiro Yoshino
Hiro Yoshino 2022 年 10 月 15 日
I would do this much more simply:
mat = [1,1,0,0,0;
1,1,1,1,0;
1,0,0,0,0;
1,1,0,0,0;
1,1,1,1,1];
% sum in row direction
answer = sum(mat,2)
answer = 5×1
2 4 1 2 5
% sort and obtain the indices
[sMat, idx] = sort(answer,"ascend");
disp("The rows ordered from weakest to strongest are")
The rows ordered from weakest to strongest are
idx
idx = 5×1
3 1 4 2 5
If you want to extract first k then:
k = 3;
idx(1:k)
ans = 3×1
3 1 4

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by