有人可以帮我解决Matlab中的以下问题吗?我有一个包含元素值的第一个向量.例如,
[2 8 4 9 3].
Run Code Online (Sandbox Code Playgroud)
并且第二个在第二个向量中具有所需的位置.例如,
[0 0 1 0 0 0 0 1 1 0 0 1 0 0 1].
Run Code Online (Sandbox Code Playgroud)
现在我想把第一个向量的值放在第二个向量的位置上
[0 0 2 0 0 0 0 8 4 0 0 9 0 0 3].
Run Code Online (Sandbox Code Playgroud)
当向量的大小非常大时,最有效的方法是什么.(那么成千上万的元素)?
小智 6
您可以将y值视为逻辑指示符,然后使用逻辑索引将这些值设置为x中的值.
x = [2 8 4 9 3];
y = [0 0 1 0 0 0 0 1 1 0 0 1 0 0 1];
y(logical(y)) = x;
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用
y(y==1) = x;
Run Code Online (Sandbox Code Playgroud)
使用自我索引:
% Your values:
V = [2 8 4 9 3];
% The desired locations of these values:
inds = [0 0 1 0 0 0 0 1 1 0 0 1 0 0 1];
% index the indices and assign
inds(inds>0) = V
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1417 次 |
| 最近记录: |