Clear Filters
Clear Filters

How to create a matrix using Booleans that looks like this:

1 view (last 30 days)
I'm trying to teach myself Matlab. I want to create a 5x5 matrix that looks like this: A= [1,1,1,1,1;6,1,1,1,1;7,7,1,1,1;8,8,8,1,1;9,9,9,9,1]
I've tested this so far:
a=@(i,j) (abs(i-j)<=1)+(i+j)+(abs(i-j)>1)*j;;A=create_matrix(a,5,5)
^^This is the closest I've gotten but it's not even close. Any hints appreciated. Thanks
I made the following script...
function [A] = create_matrix(a,n,m)
A = zeros(n,m);
for i=1:n
for j=1:m
A(i,j)=a(i,j);
end
end
end

Answers (2)

Voss
Voss on 1 Apr 2022
A = ones(5); % initialize A as a 5-by-5 matrix of all ones
for ii = 1:size(A,1)
A(ii,1:ii-1) = 4+ii; % fill in each row up to but not including the diagonal with the appropriate value
end
A
A = 5×5
1 1 1 1 1 6 1 1 1 1 7 7 1 1 1 8 8 8 1 1 9 9 9 9 1
Of course the first row remains all ones, so the loop could be for ii = 2:size(A,1)
You might also be able to use tril or other functions to do the same.
  1 Comment
Voss
Voss on 1 Apr 2022
Edited: Voss on 1 Apr 2022
Or did this need to use Booleans (known as logicals in MATLAB lingo) specifically, for some reason?
If so:
A = ones(5);
[m,n] = size(A);
[jj,ii] = meshgrid(1:m,1:n);
A(ii > jj) = ii(ii > jj)+4;
A
A = 5×5
1 1 1 1 1 6 1 1 1 1 7 7 1 1 1 8 8 8 1 1 9 9 9 9 1

Sign in to comment.


John D'Errico
John D'Errico on 2 Apr 2022
Edited: John D'Errico on 2 Apr 2022
There are always a million ways to solve such a problem, however, there is no need to use booleans at all. Best is if you learn to visualize what various tools can give you.
My immediate solution is the simple:
n = 5;
m = 5;
triu(ones(n,m)) + tril((n:2*n-1)' + zeros(1,m),-1)
ans = 5×5
1 1 1 1 1 6 1 1 1 1 7 7 1 1 1 8 8 8 1 1 9 9 9 9 1
Note that it should be fairly easy to follow what I did, and that is always important.
Even slightly simpler is this related one:
ones(n,m) + tril((n-1:2*n-2)' + zeros(1,m),-1)
ans = 5×5
1 1 1 1 1 6 1 1 1 1 7 7 1 1 1 8 8 8 1 1 9 9 9 9 1
But then you should see why this will work, and is simpler yet.
1 + tril((n-1:2*n-2)' + zeros(1,m),-1)
ans = 5×5
1 1 1 1 1 6 1 1 1 1 7 7 1 1 1 8 8 8 1 1 9 9 9 9 1
I'll quit now, before I add 5 more solutions.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!