フィルターのクリア

how can i save the even index to a matrix 2:5 using for loop

1 回表示 (過去 30 日間)
Ali ALATAWI
Ali ALATAWI 2021 年 11 月 6 日
編集済み: Chris 2021 年 11 月 6 日
i print the even position in matrix z but the qausition is to save the output of the loop which is even index into a other matrix 2:5 using for loop . this is the code to produce an even endex
clear all
clc
z=randi([1 10],5,10)
for i=1:5
if(mod(i,2)==0)
for j=1:10
if(mod(j,2)==0)
fprintf('even index:%d\n',z(i,j))
end
end
end
end

回答 (2 件)

Sargondjani
Sargondjani 2021 年 11 月 6 日
編集済み: Sargondjani 2021 年 11 月 6 日
I think you want something like this:
(which you could speed up by pre-allocating MAT=NaN(2,5))
cnt_rows = 0;
cnt_cols = 0;
for i=1:5
if(mod(i,2)==0)
cnt_rows = cnt_rows+1;
for j=1:10
if(mod(j,2)==0)
cnt_cols = cnt_cols+1;
MAT(cnt_rows,cnt_cols) = z(i,j);
end
end
end
end

Chris
Chris 2021 年 11 月 6 日
編集済み: Chris 2021 年 11 月 6 日
z=randi([1 10],5,10)
z = 5×10
10 3 6 8 4 7 10 6 2 7 8 9 7 1 1 3 2 3 4 1 6 9 3 6 8 8 2 5 2 3 7 10 9 10 8 6 2 6 7 1 6 6 8 4 6 4 2 4 10 10
newmatrix = [];
for i=1:5
if(mod(i,2)==0)
for j=1:10
if(mod(j,2)==0)
% fprintf('even index:%d\n',z(i,j))
newmatrix(end+1) = z(i,j);
end
end
end
end
newmatrix = reshape(newmatrix,5,2)'
newmatrix = 2×5
9 1 3 3 1 10 10 6 6 1
Alternatively, move down the columns in the inner loop. Then a 2x5 matrix would fill up naturally, retaining the orientation of the larger matrix.
z=randi([1 10],5,10)
newmatrix = zeros(2,5);
idx = 1;
for j=1:10
if(mod(j,2)==0)
for i=1:5
if(mod(i,2)==0)
% fprintf('even index:%d\n',z(i,j))
newmatrix(idx) = z(i,j);
idx = idx+1;
end
end
end
end
newmatrix

カテゴリ

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

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by