【问题标题】:Replace matrix elements with vector MATLAB用向量 MATLAB 替换矩阵元素
【发布时间】:2017-02-27 15:19:47
【问题描述】:

我有以下字符串矩阵:

encodedData=[1 0 1 1]

我想创建一个新的矩阵“mananalog”,将 encodedData items= 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.

您知道执行此操作的功能吗? (不用于)

【问题讨论】:

  • 是字符串还是数组?如果你在 MATLAB 中输入+encodedData,你会得到什么?
  • @StewieGriffin encodedData 是一个字符矩阵 [1001001001001100101010...]
  • Vd的内容是什么?
  • 如果你输入:+encodedData(1:4),你会得到什么?如果您提供了这些信息,那将非常有帮助... :)
  • @bushmills Vd=0.7

标签: matlab matrix


【解决方案1】:

您可以像这样使用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 或更高版本,那么 Luis 在评论中提到了 repelem

repelem(2*encodedData-1, 4)

【讨论】:

  • 完美运行!谢谢!!
  • 您知道使用 int 数字而不是字符串的方法吗?我的意思是最终矩阵将由整数组成。
  • 我试过使用 regexprep 但它只适用于字符串
  • 很棒的实现! ;)
【解决方案2】:

如果你不想在字符串和数字之间进行转换,你也可以这样做

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

【讨论】:

  • 是的,我太傻了。 repelem 绝对是这里的路。
猜你喜欢
  • 2013-09-25
  • 2013-03-14
  • 2012-11-11
  • 2017-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多