Reputation: 1307
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?
Upvotes: 0
Views: 34
Reputation: 3071
@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
Upvotes: 3
Reputation: 5128
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
Upvotes: 0