How to generate a matrix with desired pattern using nested for loops?

5 ビュー (過去 30 日間)
Alfredo Scigliani
Alfredo Scigliani 2022 年 5 月 14 日
編集済み: Dyuman Joshi 2022 年 5 月 14 日
I need to generate a 5x5 matrix like this one using nested for loops.
My first thought is to generate a zeros or ones matrix of same size and perform an operation to each term making it change to the desired one. I guess it is more complicated than I thought. Here is how I am trying to do it.
clear; clc;
A = zeros(5,5);
[numRows, numCols] = size(A);
for i = 1:numRows
for j = 1:numCols
A(i,j) = 1; %in here I would perform an operation or something that will make the specific number change.
end
end
A
% another thing that comes to my mind is to change the step from 1:numRows and 1:numCols to something like 1:2:numRows etc but it didn't work as expected.

採用された回答

Dyuman Joshi
Dyuman Joshi 2022 年 5 月 14 日
編集済み: Dyuman Joshi 2022 年 5 月 14 日
n=5;
A=zeros(n);
for i = 1:n
for j = min(i,n-i+1):max(i,n-i+1)
A(i,j) = 1;
end
end
A
A = 5×5
1 1 1 1 1 0 1 1 1 0 0 0 1 0 0 0 1 1 1 0 1 1 1 1 1

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by