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.
Show older comments
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))
% 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
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
1 Comment
Walter Roberson
on 31 Jan 2022
Not sure what the random initialization is intended to do for you, other than to waste time ?
Categories
Find more on Random Number Generation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!