【问题标题】:MATLAB : How to set matrix by matrix of index?MATLAB:如何按索引矩阵设置矩阵?
【发布时间】:2018-09-09 11:54:17
【问题描述】:

我想问一下如何在MATLAB中设置矩阵:

|1 4 5|
|2 9 1| =A,
|5 1 3|

|1 3 2|
|2 1 3| =INDEX,它表示哪些位置应该放置矩阵 A 的元素
|3 2 1|

像这样:(这将是一个输出)

|1 5 4|
|9 2 1| =矩阵,
|3 1 5|

很高兴得到答复:) 谢谢

【问题讨论】:

  • 将 A 和 B 定义为 A=([1,4,5;2,9,1;5,1,3])'B=[1,3,2;2,1,3;3,2,1]+[0,0,0;3,3,3;6,6,6] 然后应用 A(B)(它不是一个优雅的索引,但确实有效)

标签: matlab matrix indexing


【解决方案1】:

这里提供了两种解决方案:

使用accumarray

[row_idx, ~] = find(INDEX);
result = accumarray([row_idx(:) INDEX(:)], A(:), size(A));

使用sub2ind

s = size(A);
row_idx = repmat((1:s(1)).', 1, s(2));
idx = sub2ind(s, row_idx, INDEX);
result = reshape(A(idx), s);

【讨论】:

    猜你喜欢
    • 2011-12-24
    • 1970-01-01
    • 2018-03-26
    • 2015-07-10
    • 2014-05-12
    • 2013-09-13
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多