MATLAB: Accessing values in a Cell Array using Index Values stored in another array

array indexingcell arrays

Hi All,
I have some data stored in a 1×15 cell array. I am trying to access that data using index values stored in another array. The code my help to explain the problem.
I have a 1×15 array called NewVector
NewVector = [1.5 1.5 2.1 2.2 2.2 2.2 2.2 0.9 0.8 2.4 2.3 2.8 2.4 2.9 3.1]
I then create an array storing the indices of the values I want from NewVector. In this case values 2.8 and 2.9 (index position 12 and 14 respectively) .
index = find(NewVector > 2.7 & NewVector < 3.0) % Obatin index values and store
I then want to use these values to access data in my 1×15 cell array called NewSpeed i.e. I want to access values {1,12} and {1,14}.
So far I have the code below, but it doesn’t give the correct result…
l= length(index)
for x =1: length(index)
t = index(1:x)
CellVal(:,x) = NewSpeed{1,t}
end
Any help would be appreciated.
Thanks
Ben

Best Answer

That requires a bit of cell array gymnastics:
NewVector = [1.5 1.5 2.1 2.2 2.2 2.2 2.2 0.9 0.8 2.4 2.3 2.8 2.4 2.9 3.1];
NewVectorCell = mat2cell(NewVector,1);
index = cellfun(@(x)find(x > 2.7 & x < 3.0), NewVectorCell, 'Unif',0); % Obatin index values and store
SelectNewVectorCell = NewVectorCell{:}([index{:}])
producing:
SelectNewVectorCell =
2.8 2.9
.