简体   繁体   English

Matlab或R:用另一个矩阵中的值依次替换矩阵中的元素

[英]Matlab or R: replace elements in matrix by values from another matrix in order

I have a problem to solve in either Matlab or R (preferably in R). 我在Matlab或R(最好在R)中要解决的问题。

Imagine I have a vector A with 10 elements. 想象一下,我有一个包含10个元素的向量A。

I have also a vector B with 30 elements, of which 10 have value 'x'. 我还有一个包含30个元素的向量B,其中10个具有值“ x”。

Now, I want to replace all the 'x' in B by the corresponding values taken from A, in the order that is established in A . 现在,我要按照在A中建立的顺序,用从A 获取的相应值替换B中的所有“ x”。 Once a value in A is taken, the next one is ready to be used when the next 'x' in B is found. 一旦获取了A中的一个值,当在B中找到下一个“ x”时,就可以使用下一个。

Note that the sizes of A and B are different, it's the number of 'x' cells that coincides with the size of A. 请注意,A和B的大小不同,这是“ x”像元的数量与A的大小一致。

I have tried different ways to do it. 我尝试了不同的方法。 Any suggestion on how to program this? 关于如何编程的任何建议?

As long as the number of x entries in B matches the length of A , this will do what you want: 只要B中的x个条目的数量与A的长度匹配,就可以完成您想要的操作:

B[B=='x'] <- A

(It should be clear that this is the R solution.) (应该清楚这是R解决方案。)

MATLAB Solution MATLAB解决方案

In MATLAB it's quite simple, use logical indexing: 在MATLAB中,它非常简单,请使用逻辑索引:

B(B == 'x') = A;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM