problem with vector logic
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Why doesn't the final logical operation work?
Oneigh=zeros(10,10);
r = round(0.5+rand(10,10)*8);
Oneigh(r==1)=r;
For the elements where r==1, Oneigh should adopt the corresponding value in r.
By the way for the operation:
Oneigh(r==1)=r;
should actually be
Oneigh(r==1)=O1;
where O1 is another matrix of the same size, but the above is simpler and not working.
0 Commenti
Risposte (2)
Geoff Hayes
il 2 Ott 2014
Christopher - if you run the following code, the line
Oneigh(r==1)=r;
is probably generating the
In an assignment A(I) = B, the number of elements in B and I must be the same.
error message. Look closely at what is happening
>> r==1
ans =
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 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 1 0 0
1 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 1 0 0 0 1 0 1 0
0 0 0 0 0 0 0 0 0 0
is a 10x10 matrix. Now look at
>> Oneigh(r==1)
ans =
0
0
0
0
0
0
0
0
0
is a 9x1 vector corresponding to the elements of Oneigh indexed on the logical matrix generated by r==1. So
Oneigh(r==1)=r;
tries to assign a 10x10 matrix (r) to the 9x1 column vector, and the error makes sense.
As you say, for the elements where r==1, Oneigh should adopt the corresponding value in r, then this could be simplified to
Oneigh(r==1)=1;
since the corresponding value in r is 1.
Else, if you know the indices in r that are identical to 1, then we can use that information to update Oneigh given O1 as
idcs = find(r==1);
Oneigh(idcs) = O1(idcs);
0 Commenti
Star Strider
il 2 Ott 2014
If you want ‘Oneigh’ to be a matrix with only any particular value of ‘r’ existing and with zeros elsewhere, It’s a bit more involved but still relatively straightforward:
Oneigh=zeros(10,10);
r = round(0.5+rand(10,10)*8);
iv = 1; % Integer To Match
q = r==iv; % Logical Array
Oneigh = r; % Assign ‘Oneigh’ As ‘r’
Oneigh(~q) = 0; % ‘Oneigh’ Now Has ‘iv’ Matching ‘r’, Zero Elsewhere
Note that in this method there is actually no need to preallocate ‘Oneigh’. I retained it for consistency. You can also use the randi function to generate ‘r’.
0 Commenti
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements 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!