Create some simple Matlab code that will generate square matrices that have ones above the leading diagonal, and zeros on and below the leading diagonal.

I need to use simple codes like if, for, while, elseif...etc statments.
example of end product: [0 1 1 1;0 0 1 1;0 0 0 1;0 0 0 0 ]

Answers (2)

Hint:
A = triu(ones(4))
A = 4×4
1 1 1 1 0 1 1 1 0 0 1 1 0 0 0 1
% Or, you can use your code, with r <= c instead of r < c
nrows = 4; % number of row
ncols = 4; % number of column
A = zeros(nrows,ncols); % Initialize to all zeros.
for c = 1:ncols
for r = 1:nrows
if r<=c
A(r,c) = 1;
end
end
end
A
A = 4×4
1 1 1 1 0 1 1 1 0 0 1 1 0 0 0 1
nrows = 4; % number of row
ncols = 4; % number of column
A = randi([1 10],nrows,ncols); % creating random integer number between 1 to 10.
for c = 1:ncols
for r = 1:nrows
if r == c
A(r,c) = 0;
elseif r<c
A(r,c) = 1;
else
A(r,c) = 0;
end
end
end
A
A = 4×4
0 1 1 1 0 0 1 1 0 0 0 1 0 0 0 0

1 Comment

Not sure what the random initialization is intended to do for you, other than to waste time ?

Sign in to comment.

Categories

Find more on Random Number Generation in Help Center and File Exchange

Asked:

on 30 Jan 2022

Commented:

on 31 Jan 2022

Community Treasure Hunt

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

Start Hunting!