How to add elements to a matrix one-by-one?
조회 수: 5 (최근 30일)
이전 댓글 표시
I have a matrix [0 1; 1 0]. I need to:
1) choose random row from this matrix
2) duplicate every non-zero element from this row with a some probability and add it to the matrix.
3) enlarge the size of the matrix (to keep it square)
4) repeate the procedure with the new matrix (with added row), say, 10 times.
The idea is to use this matrix to construct a graph (where zeros correspond to the absence of linkadge between two nodes and ones - to the presence of linkadge).
Now I stuck on the stage of enlarging the matrix: as every element of the randomly chosen row should be checked alone, matlab do not allow to add elements one-by-one in one cycle.
conmat = [0 1; 1 0] ;
S=size(conmat,1);
r=randi(S);
sigma=0.3;
a=rand;
rndrow=conmat(r,:);
rowadd=[];
for j=1:size(conmat,1);
if sigma>a
rowadd(j)=[rowadd rndrow(j)]
elseif sigma<a
rowadd(j)= [0]
end
conmat=[conmat rowadd] %ERROR
coladd=transpose(conmat(3,:))
coladd=[coladd; 0]
conmat=[conmat coladd]
end
Error using horzcat
Dimensions of arrays being concatenated are not consistent.
Error in network_181129 (line 15)
conmat=[conmat rowadd]
I feel I need to use some different approach not syntaxis tricks but I'm not so experinced in coding and Matlab and already spent a lot of time on this problem. I will appreciate any help and ideas, thank you in advance!
댓글 수: 0
채택된 답변
Luna
2018년 12월 6일
편집: Luna
2018년 12월 6일
Hi,
I tried to fix the errors (cut and paste some lines inside the inner for loop), and added outer for loop for 10 times calculation(I assume your random variable a changes in every iteration).
Try this below. It takes a little bit long time since I ended up with conmat 2048x2048 matrix. But maybe there could be a high performanced version of it.
conmat = [0 1; 1 0] ;
for m=1:10
S=size(conmat,1);
r=randi(S);
sigma=0.3;
a=rand;
for j=1:size(conmat,1)
rowadd=zeros(1,size(conmat,1));
rndrow=conmat(r,:);
if sigma > a
rowadd= rndrow;
elseif sigma < a
% rowadd(j)= 0
end
conmat=[conmat; rowadd]; %ERROR
coladd=transpose(conmat(3,:));
coladd=[coladd; 0];
conmat=[conmat coladd];
end
end
If you want to replicate matrices you can use repmat function also. Here the link: repmat
댓글 수: 2
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!