3

Is there a way in Matlab to select a matrix element based off the elements in a vector? I don't think my description is clear, but what I effectively want to do is something similar to:

A=zeros(3,3,3) %3d matrix
A(1,1,2)=5
b=[1,1,2]
A(b)=5

Meaning, some easy way to select one element from a matrix using the entries in a vector as arguments. This exact example does not work because the last line counts b as a single argument, not three. I could write A(b(1),b(2),b(3)) but what I'm really looking for here is if there's a nice way of doing.

dan479
  • 43
  • 3

1 Answers1

0

Method 1: Use sub2ind to find the linear index

You can define a function called findLinearIndex such that it convert the vector elements to the linear index of A:

findLinearIndex = @(A,b) sub2ind(size(A), b(1), b(2), b(3))
A(findLinearIndex(A,b)) = 5

Method 2: Convert the vector to cell array by num2cell

Then, you can use {:} to get the index

b_cell = num2cell(b) ;
A(b_cell{:}) = 5
Banghua Zhao
  • 1,518
  • 1
  • 14
  • 23