matlab - how to Conditionally add values to a matrix without using a for loop? -


i have written loop code , want write in more succinct way without using for loop, instead use matrix conditional. teaching myself matlab , appreciate feedback.

i want create new matrix, first column y, , second column filled 0 except y's indices contained in indices matrix. , in latter case, add 1 instead of 0.

thanks.

y=[1;2;3;4;5;6;7]; indices=[1;3;5]; [m,n]=size(y); tem=zeros(m,1);  data=[y,tem];  [r,c]=size(indices); i=1:r   a=indices(i);   data(a,2 )=1; end  output:  data =   1     1  2     0  3     1  4     0  5     1  6     0  7     0 

a shorter alternative:

data = [y(:), full(sparse(indices, 1, 1, numel(y), 1))]; 

the resulting matrix data composed of 2 column vectors: y(:) , sparse array, "1"s @ positions corresponding indices.

using proper initialization , sparse matrices can useful in matlab.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -