How to pick elements of several arrays via assigned vector
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Warren Chuo
am 14 Jun. 2021
Kommentiert: Warren Chuo
am 21 Jun. 2021
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 Kommentare
SALAH ALRABEEI
am 14 Jun. 2021
what is exactly do you want! How the vec_i is related to the matrix index!
Akzeptierte Antwort
Shivam Malviya
am 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)
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Crystals finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!