How to pick elements of several arrays via assigned vector

1 view (last 30 days)
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 Comments
SALAH ALRABEEI
SALAH ALRABEEI on 14 Jun 2021
what is exactly do you want! How the vec_i is related to the matrix index!
Warren Chuo
Warren Chuo on 14 Jun 2021
Edited: Warren Chuo on 14 Jun 2021
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;

Sign in to comment.

Accepted Answer

Shivam Malviya
Shivam Malviya on 15 Jun 2021
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 Comment
Warren Chuo
Warren Chuo on 21 Jun 2021
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.

Sign in to comment.

More Answers (0)

Products


Release

R2010b

Community Treasure Hunt

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

Start Hunting!