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

3 次查看(过去 30 天)
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

采纳的回答

Matt J
Matt J 2022-7-5
编辑:Matt J 2022-7-5
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by