# create a sparse multidimensional matrix

조회 수: 4 (최근 30일)
편집: Jonas 2022년 7월 7일
Hi all,
I am trying to construct a multidimensional sparse matrix that has the following shape:
I have a problem knowing how to jump from column to the next, shift the rows downwards, and assign number 1 to the third element.
Any help would be appreicted.
Thanks.

댓글을 달려면 로그인하십시오.

### 답변 (5개)

Jonas 2022년 7월 7일
편집: Jonas 2022년 7월 7일
you can try this:
myData=[1 2 3 4;
5 6 7 8;
9 10 11 12];
% get sizes
dataChunkLength=size(myData,2);
numOfChunks=size(myData,1);
% preallocate
mat=zeros(dataChunkLength*numOfChunks,numOfChunks);
for colNr=numOfChunks:-1:1
% write
mat(1:dataChunkLength,colNr)=myData(colNr,:);
if colNr>1
% and shift along first dimension
mat=circshift(mat,dataChunkLength,1);
end
end
disp(mat)
1 0 0 2 0 0 3 0 0 4 0 0 0 5 0 0 6 0 0 7 0 0 8 0 0 0 9 0 0 10 0 0 11 0 0 12
or, if you waqnt to write alswys the same data
myData=[0 0 1 0];
% get length
dataChunkLength=numel(myData);
% write to n columns
nTimes=5;
% preallocate
mat=zeros(dataChunkLength*nTimes,nTimes);
for colNr=nTimes:-1:1
% write
mat(1:dataChunkLength,colNr)=myData;
if colNr>1
% and shift along first dimension
mat=circshift(mat,dataChunkLength,1);
end
end
disp(mat)
0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0
##### 댓글 수: 0이전 댓글 -2개 표시이전 댓글 -2개 숨기기

댓글을 달려면 로그인하십시오.

Torsten 2022년 7월 7일
i(1) = 3;
j(1) = 1;
v(1) = 1.0;
i(2) = 7;
j(2) = 2;
v(2) = 1.0;
i(3) = 11;
j(3) = 3;
v(3) = 1.0;
m = 12;
n = 3;
A = sparse(i,j,v,m,n)
A =
(3,1) 1 (7,2) 1 (11,3) 1
##### 댓글 수: 0이전 댓글 -2개 표시이전 댓글 -2개 숨기기

댓글을 달려면 로그인하십시오.

Karim 2022년 7월 7일
you can either fill it in directly or use blkdiag to create this shape:
% direct method
% on row 3 7 and 11, column 1 2 3 respectivly, fill in 1, with 12 rows and 3 columns
SparseDirect = sparse([3 7 11],[1 2 3],1,12,3)
SparseDirect =
(3,1) 1 (7,2) 1 (11,3) 1
% alternative using blkdiag
A = sparse( [0;0;1;0] );
B = sparse( [0;0;1;0] );
C = sparse( [0;0;1;0] );
SparseMat = blkdiag(A,B,C)
SparseMat =
(3,1) 1 (7,2) 1 (11,3) 1
% full visualisation
full(SparseMat)
ans = 12×3
0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0
##### 댓글 수: 0이전 댓글 -2개 표시이전 댓글 -2개 숨기기

댓글을 달려면 로그인하십시오.

Matt J 2022년 7월 7일
n=3;
A=kron(speye(n),[0;0;1;0])
A =
(3,1) 1 (7,2) 1 (11,3) 1
full(A)
ans = 12×3
0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0
##### 댓글 수: 0이전 댓글 -2개 표시이전 댓글 -2개 숨기기

댓글을 달려면 로그인하십시오.

KSSV 2022년 7월 7일
A = sparse(12,3) ;
A(3,1) = 1 ;
A(7,2) = 1 ;
A(11,3) = 1 ;
A
A =
(3,1) 1 (7,2) 1 (11,3) 1
full(A)
ans = 12×3
0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0

댓글을 달려면 로그인하십시오.

### 카테고리

Help CenterFile Exchange에서 Sparse Matrices에 대해 자세히 알아보기

### Community Treasure Hunt

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

Start Hunting!

Translated by