2016-10-18 34 views
1

替换矩阵元素我有以下的字符串矩阵:与矢量MATLAB

encodedData=[1 0 1 1] 

我想创建一个新的矩阵“mananalog”代替encodedData项= 1与[1 1 1 1]和0与[ - 1 -1 -1 -1]

最终基质mananalog将是:[1 1 1 1 -1 -1 -1 -1 1 1 1 1 1 1 1 1]

我使用尝试以下代码:

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

不过,我有以下错误:

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

你知道的功能,从而做到这一点? (未使用)

+0

它是一个字符串或数组?如果你在MATLAB中输入'+ encodedData',你会得到什么? –

+0

@StewieGriffin encodedData是一个char矩阵[1001001001001100101010 ...] –

+0

'Vd'的内容是什么? – bushmills

回答

3

您可以使用regexprepstrrep这样的:

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 

这是一个有点简单,如果你使用,虽然两条线路:

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

这将首先搜索字符'1',并用字符串替换它:'1 1 1 1'。然后它搜索'0'并用字符串'-1 -1 -1 -1'替换它。

用整数,而不是字符:

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 

而且,如果你有MATLAB R2015a或更高版本则有repelem作为路易斯在评论中提到:

repelem(2*encodedData-1, 4) 
+0

完美的作品!谢谢!! –

+0

你知道如何使用int数字而不是字符串来做到这一点吗?我的意思是最终的矩阵将由整数组成。 –

+0

我试过使用正则表达式,但它只适用于字符串 –

1

如果你不想字符串和数字之间的转换,你也可以做

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

又'repelem(2 * encodedData-1,4)' –

+0

是的,那对我来说很愚蠢。 'repelem'绝对是这里走的路。 – CKT