How to pick elements of several arrays via assigned vector

조회 수: 1 (최근 30일)
Warren Chuo
Warren Chuo 2021년 6월 14일
댓글: Warren Chuo 2021년 6월 21일
Hi,
I have 3 arrays, and would like to form new array picking elements from these 3 arrays.
The picking is via my assigned vector.
The computation should be matrix computation, no for loop inside.
e.g.
-----
[input]
arr_i1 = [111,112,113,114; ...
121,122,123,124];
arr_i2 = [211,212,213,214; ...
221,222,223,224];
arr_i3 = [311,312,313,314; ...
321,322,323,324];
vec_i = [2,3,1,2];
[output]
arr_o = [211,312,113,214; ...
221,322,123,224];
-----
Your answer would be quite appreciated.
  댓글 수: 3
SALAH ALRABEEI
SALAH ALRABEEI 2021년 6월 14일
what is exactly do you want! How the vec_i is related to the matrix index!
Warren Chuo
Warren Chuo 2021년 6월 14일
편집: Warren Chuo 2021년 6월 14일
Thank you for comments.
To make my question more clear:
arr_i = cat(3,arr_i1,arr_i2,arr_i3);
the function(e.g. func_pick) I want to seek is
arr_o = func_pick(arr_i,vec_i);
Detail in/out relationship of this function is:
arr_o(1:2,1) = arr_i(1:2,1,2), since vec_i(1) == 2;
arr_o(1:2,2) = arr_i(1:2,2,3), since vec_i(2) == 3;
arr_o(1:2,3) = arr_i(1:2,3,1), since vec_i(3) == 1;
arr_o(1:2,4) = arr_i(1:2,4,2), since vec_i(4) == 2;

댓글을 달려면 로그인하십시오.

채택된 답변

Shivam Malviya
Shivam Malviya 2021년 6월 15일
Hi Warren!
You can find the implementation of the func_pick function below: -
func_pick.m
function arr_o = func_pick(arr_i, v)
d3 = v;
d2 = 1:length(d3);
d1 = [1:size(arr_i, 1)]';
i1 = repmat(d1, 1, length(d2));
i2 = repmat(d2, length(d1), 1);
i3 = repmat(d3, length(d1), 1);
i123 = cat(3, i1, i2, i3) - 1;
linear_i = i123(:, :, 1) + size(arr_i, 1) * (i123(:, :, 2) + size(arr_i, 2) * i123(:, :, 3)) + 1
arr_o = arr_i(linear_i);
end
script.m
a1 = [111,112,113,114;
121,122,123,124];
a2 = [211,212,213,214;
221,222,223,224];
a3 = [311,312,313,314;
321,322,323,324];
arr_i = cat(3, a1, a2, a3);
v = [2, 1, 3, 2];
arr_o = func_pick(arr_i ,v)
  댓글 수: 1
Warren Chuo
Warren Chuo 2021년 6월 21일
Hi, Shivam Malviya,
Thank you for your wise input, and I'm very sorry to respond this late.
Somebody suggested me 'sub2ind' and manipulate indices instead of values.
After few optimizing steps, I found out a straightforward way to just cover my real issues efficiently.
Your suggested function can lead to expected result very well.
Just I need few moment to digest the arithmetic relationship inside this function.
Anyway, your input is very appreciated.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

제품


릴리스

R2010b

Community Treasure Hunt

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

Start Hunting!

Translated by