Replacing several values in multidimensional array simultaneously

12 ビュー (過去 30 日間)
David Hoffmeyer
David Hoffmeyer 2020 年 9 月 14 日
編集済み: Bruno Luong 2020 年 9 月 14 日
I have a multidimensional array, e.g.
A(:,:,1) = [1 2 3 ; 4 5 6];
A(:,:,2) = [7 8 9 ; 10 11 12];
I want to replace several of the values in this array with the same value simultaneously. Specifically I want to do this column-wise, the result should be e.g.
A(:,2,1) = [-1 ; -2];
A(:,3,2) = [-1 ; -2];
yielding
A(:,:,1) = [1 -1 3 ; 4 5 -1];
A(:,:,2) = [7 -2 9 ; 10 11 -2];
I attempted this by
B = [2 3]; C = [1 2];
A(:,B,C) = [-1 ; -2];
but it does not give the wanted result.
Any idea on how to do this without performing a for-loop?

採用された回答

Bruno Luong
Bruno Luong 2020 年 9 月 14 日
編集済み: Bruno Luong 2020 年 9 月 14 日
A(:,:,1) = [1 2 3 ; 4 5 6];
A(:,:,2) = [7 8 9 ; 10 11 12];
s = size(A);
A(:, sub2ind(s(2:3),[2 3],[1 2])) = 0 % = [0 0; 0 0]
  2 件のコメント
David Hoffmeyer
David Hoffmeyer 2020 年 9 月 14 日
編集済み: David Hoffmeyer 2020 年 9 月 14 日
Thanks for your input. However, I have not been precise enough in my question. I need to replace a number of columns in the array with a column containing non-identical values (see the edited question), and not just 0. In that case your proposal does not work. Can you alter it correspondingly?
Bruno Luong
Bruno Luong 2020 年 9 月 14 日
編集済み: Bruno Luong 2020 年 9 月 14 日
Just replace the RHS as I hint in my answer with "% = [0 0; 0 0]"
A(:, sub2ind(s(2:3),[2 3],[1 2])) = [[-1;-2], [-1;-2]]

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by