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

3 ビュー (過去 30 日間)
nobody
nobody 2022 年 7 月 5 日
編集済み: Matt J 2022 年 7 月 5 日
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 Center および File ExchangeCreating 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