How can I access the elements of one array with another array?

I'd like to assign elements to an array in the following manner:
a = zeros(2,2,2);
ix=1;
iy=1;
b = [1,1];
a([ix,iy],:) = b(:)
Where ix and iy represent the position in the 1st and 2nd directions, a in it's 3rd dimension and b are the same length length. For my application ix and iy really need to be in the same array and the method needs to be applicable to N-dimensions. Is there a way to do such an assignment?

 採用された回答

Stephen23
Stephen23 2018 年 12 月 11 日
編集済み: Stephen23 2018 年 12 月 11 日

2 投票

This is really very easy once you put those indices into a cell array:
C = {ix,iy,...,iN,':'};
a(C{:}) = b
Given a numeric vector of indices V:
V = [ix,iy,...,iN];
C = num2cell(V);
a(C{:},':') = b;
or
a(C{:},:) = b;

その他の回答 (2 件)

KSSV
KSSV 2018 年 12 月 11 日

0 投票

a = zeros(2,2,2);
ix=1;
iy=1;
b = [1,1];
a(ix,iy,:) = b

1 件のコメント

Ryan Potter
Ryan Potter 2018 年 12 月 11 日
Sorry, but I would like to be able to extend this to N-dimensions without writing:
a(ix,iy,...,iN,:) = b
The indices [ix,iy,...,iN] are generated programmatically the length varies.

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

Guillaume
Guillaume 2018 年 12 月 11 日

0 投票

I'm going to assume that [ix, iy] is a 2D array, not a vector as in your example, otherwise your problem is trivially solved with:
indices = [ix, iy];
a(indices(1), indices(2), :) = b(:);
If it's a vector, you will have to convert your Nd subscripts into linear indices with sub2ind. Unfortunately, that means you can't use the colon operator. You have to explicitly list the dimensions.
a = zeros(2, 2, 2);
indices = [1 1;1 2;2 1];
b = [1 2; 3 4; 5 6] %shape of b doesn't matter
linindices = sub2ind(size(a), repmat(indices(:, 1), 1, size(a, 3)), repmat(indices(:, 2), 1, size(a, 3)), repmat(1:size(a, 3), size(indices, 1), 1))
a(linindices) = b

2 件のコメント

Ryan Potter
Ryan Potter 2018 年 12 月 11 日
[ix, iy] is a vector, but the size of 'a' varies programmatically as do the indices so the vector could look like indices [ix,iy,...,iN]. And I'd like to assign values as follows
a(ix,iy,...,iN,:) = b
I'll investigate linear indices in the meantime.
Guillaume
Guillaume 2018 年 12 月 11 日
編集済み: Guillaume 2018 年 12 月 11 日
Ah ok, In that case, see Stephen's answer

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

カテゴリ

ヘルプ センター および File ExchangeResizing and Reshaping Matrices についてさらに検索

製品

リリース

R2018b

タグ

質問済み:

2018 年 12 月 11 日

編集済み:

2018 年 12 月 11 日

Community Treasure Hunt

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

Start Hunting!

Translated by