简体   繁体   中英

Put matrix in place of value within a matrix

I know the title is confusing, but I can't come up with a better way to explain it. Basically, I have a matrix of ones and zeros, for the sake of the example:

a = [1 0 1 0 1 1 0 0];

What I want to get is:

if (a == 1)
    a (that index) = [1 0]
if (a == 0)
    a (that index) = [-1 0]

such that:

a = [1 0 -1 0 1 0 -1 0 1 0 1 0 -1 0 -1 0]

I can't seem to find a way to do this, since matlab won't let me set individual indices to something that's larger than a single digit (makes sense).

So far I've tried (with a few minor syntax variations):

SM = [[1, 0]; [-1, 0]];
a = SM(a + 1);

That's from legacy code that used:

SM = [1, -1];
a = SM(a + 1);

which worked properly

Is there a way to do this without first building a properly sized array, and filling it in a loop?

@nalyd88's answer is correct, but I think that the use of cells is unnecessary here. Another solution can be:

a = [1 0 1 0 1 1 0 0]
b=zeros(1,length(a)*2);
b(find(a)*2-1)=1;
b(find(~a)*2-1)=-1

b =

 1     0    -1     0     1     0    -1     0     1     0     1     0    -1     0    -1     0

And a neat solution with one line is with kron , that is a little bit more difficult to read, or understand, but these problems is especially for this function...

b=kron(a,[1 0])+kron(~a,[-1 0])
b =

 1     0    -1     0     1     0    -1     0     1     0     1     0    -1     0    -1     0

Does this solve your problem?

a = [1 0 1 0 1 1 0 0];
b = num2cell(a);      % Convert to cell array (each value is a cell)
b(a == 1) = {[1 0]};  % Replace ones (logical indexing)
b(a == 0) = {[-1 0]}; % Replace zeros (logical indexing)
cell2mat(b)           % Flatten back into a vector.

The output is:

ans =

     1     0    -1     0     1     0    -1     0     1     0     1     0    -1     0    -1     0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM