How to create a matrix using Booleans that looks like this:
조회 수: 1 (최근 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!