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
0 个评论
回答(2 个)
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
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.
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)
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)
But then you should see why this will work, and is simpler yet.
1 + tril((n-1:2*n-2)' + zeros(1,m),-1)
I'll quit now, before I add 5 more solutions.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!