필터 지우기
필터 지우기

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

조회 수: 1 (최근 30일)
V_Izepatchy
V_Izepatchy 2022년 4월 1일
편집: John D'Errico 2022년 4월 2일
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