fill a vector (efficiently) with values specified by matrix and multiple vectors

4 views (last 30 days)
Hi,
I need to run this problem efficiently (because it will run a billion times or more)
There is a fixed 2x2x2 matrix M
Each time the code runs, there are three vectors x,y,z of length N corresponding to the same entitities.
their values are 1 or 2, because the correspond to matrix M. So that each entity is linked to a element of M. I.e. value I want for entity 1: M(x(1),y(1),z(1))
So my goal is to have a vector of length N filled with the values I want BUT
as efficiently as possible (one line?)
I currently do it for only two vectors like this
M=reshape(1:8,2,2,2);N=10;
x=(rand(N,1)>0.5)+1;y=(rand(N,1)>0.1)+1;z=(rand(N,1)>0.1)+1;
tmp=M(x,y,z(1)); %which creates a N by N matrix instead of a vector
%NOTE: this uses z(1), but I would like to use the whole vector z
OUT=tmp(1:N+1:end); %which extracts the diagonal, which are the values I want
Any suggestions appreciated
PS:
I currently have Corona and can't figure out how I need to replace "1:N+1:end" to deal with a N by N by N matrix, which would work (unlike my brain right now)
BUT
if N~100 that matrix (which I don't need) gets pretty big and probably slows it all down. So would nice to avoid that

Accepted Answer

Matt J
Matt J on 5 Jul 2022
Edited: Matt J on 5 Jul 2022
M=reshape(1:8,2,2,2);N=10;
x=(rand(N,1)>0.5)+1;y=(rand(N,1)>0.1)+1;z=(rand(N,1)>0.1)+1;
OUT=M( sub2ind(size(M),x,y,z) )
OUT = 10×1
7 7 7 6 7 7 7 8 7 7

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!