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

3 次查看(过去 30 天)
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

回答(2 个)

Voss
Voss 2022-4-1
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 个评论
Voss
Voss 2022-4-1
编辑:Voss 2022-4-1
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

请先登录,再进行评论。


John D'Errico
John D'Errico 2022-4-2
编辑:John D'Errico 2022-4-2
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.

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by