MM Manuel
MM Manuel

Reputation: 385

Replace matrix elements with vector MATLAB

I have the following string matrix:

encodedData=[1 0 1 1]

I want to create a new Matrix "mananalog" replacing encodedData items= 1's with [1 1 1 1] and 0's with [-1 -1 -1 -1]

Final matrix mananalog would be: [1 1 1 1 -1 -1 -1 -1 1 1 1 1 1 1 1 1]

I've tried using the following code:

mananalog(find(encodedData=='0'))=[num2str(1*(-Vd)) num2str(1*(-Vd)) num2str(1*(-Vd)) num2str(1*(-Vd))];
mananalog(find(encodedData=='1'))=[num2str(1*(Vd)) num2str(1*(Vd)) num2str(1*(Vd)) num2str(1*(Vd))];

vd=0.7

Nevertheless, i have the following error:

In an assignment  A(I) = B, the number of elements in B and I must be the same.

Do you know the function so as to do this? (Not using for)

Upvotes: 1

Views: 121

Answers (2)

Stewie Griffin
Stewie Griffin

Reputation: 14939

You can use regexprep or strrep like this:

encodedData='1 0 1 1'
regexprep(regexprep(encodedData, '1', '1 1 1 1'),'0','-1 -1 -1 -1')
ans =
1 1 1 1 -1 -1 -1 -1 1 1 1 1 1 1 1 1

It's a bit simpler if you use two lines though:

encodedDataExpanded = regexprep(encodedData, '1', '1 1 1 1');
encodedDataExpanded = regexprep(encodedDataExpanded , '0', '-1 -1 -1 -1')

This will first search for the character '1' in the string, and replace it with the string: '1 1 1 1'. Then it search for '0' and replaces it with the string '-1 -1 -1 -1'.

With integers, not characters:

encodedData = [1 0 1 1];
reshape(bsxfun(@minus, 2*encodedData, ones(4,1)), 1, [])
ans =    
   1   1   1   1  -1  -1  -1  -1   1   1   1   1   1   1   1   1

And, if you have MATLAB R2015a or later then there's repelem as Luis mentioned in a comment:

repelem(2*encodedData-1, 4)

Upvotes: 3

CKT
CKT

Reputation: 781

If you don't want to convert between strings and numerics, you can also do

>> kron(encodedData, ones(1,4)) + kron(1-encodedData, -ones(1,4))

Upvotes: 1

Related Questions