How to add elements to a matrix one-by-one?
5 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
Luna
il 6 Dic 2018
Modificato: Luna
il 6 Dic 2018
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
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Resizing and Reshaping Matrices in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!