How to use nested loop to produce the row and columns like that

16 ビュー (過去 30 日間)
Shuoze Xu
Shuoze Xu 2022 年 3 月 22 日
コメント済み: Mathieu NOE 2022 年 3 月 22 日
Given a 2D array, called A, of size 5 x 5,
Sample Output: Given A = [2,4,8,7,3;2,2,3,4,3;5,5,4,2,7;8,2,7,3,9;1,2,3,4,5];
output:
2 4 8 7 3
2 2 3
5 5 7
8 2 7 3 9
1 2 3 4 5
% My code
A = [2,4,8,7,3;2,2,3,4,3;5,5,4,2,7;8,2,7,3,9;1,2,3,4,5];
rows = size(A,1) % the number of rows in A
columns = size(A,2) % the number of columns in A
B = [];
for row = 1:rows
for column = 1:columns
if (row == 2 || row == 3)
if (column == 3 || column == 4)
B = [B A(i)]
end
end
end
end
disp(B);
My code is wrong i thought

採用された回答

Mathieu NOE
Mathieu NOE 2022 年 3 月 22 日
hello
seems to me B is simply A but rows 2 and 3 for columns 3 and 4 are empty (filled with NaN)
code :
A = [2,4,8,7,3;2,2,3,4,3;5,5,4,2,7;8,2,7,3,9;1,2,3,4,5];
B = A;
B(2:3,3:4) = NaN;
results :
A =
2 4 8 7 3
2 2 3 4 3
5 5 4 2 7
8 2 7 3 9
1 2 3 4 5
B =
2 4 8 7 3
2 2 NaN NaN 3
5 5 NaN NaN 7
8 2 7 3 9
1 2 3 4 5
  4 件のコメント
Shuoze Xu
Shuoze Xu 2022 年 3 月 22 日
Wow, it works.
Thank you so much
Mathieu NOE
Mathieu NOE 2022 年 3 月 22 日
My pleasure !

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

その他の回答 (1 件)

Arif Hoq
Arif Hoq 2022 年 3 月 22 日
you did not clear your expection. you can try this
A = [2,4,8,7,3;2,2,3,4,3;5,5,4,2,7;8,2,7,3,9;1,2,3,4,5];
rows = size(A,1); % the number of rows in A
columns = size(A,2); % the number of columns in A
B = [];
for row = 1:rows
for column = 1:columns
% if row == 2 || row == 3 && column == 3 || column == 4
if (row == 2 || row == 3)
if (column == 3 || column == 4)
B = [B A(row)]
end
end
end
end
B = 2
B = 1×2
2 2
B = 1×3
2 2 5
B = 1×4
2 2 5 5
disp(B);
2 2 5 5
  2 件のコメント
Shuoze Xu
Shuoze Xu 2022 年 3 月 22 日
My expectation is to remove the elements in the third and fourth columns of the second row, and the third and fourth columns of the third row and print the array.
Shuoze Xu
Shuoze Xu 2022 年 3 月 22 日
using the nested loop

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by