2016-10-18 36 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