Accessing values in a Cell Array using Index Values stored in another array
12 ビュー (過去 30 日間)
古いコメントを表示
Hi All,
I have some data stored in a 1x15 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 1x15 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 1x15 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
2 件のコメント
sushanth govinahallisathyanarayana
2020 年 9 月 22 日
You could use simple logical indexing, for example,
indexedValues=array(index);
where index is the result of NewVector > 2.7 & NewVector < 3.0
If this is from a cell array, you could try array{element}(index) while traversing the array in a loop.
If you want to avoid loops altogether, you can use cellfun, but that requires you to have newvector and index as cell arrays as well, you can easily convert these using mat2cell or num2cell.
Hope this helps.
採用された回答
Star Strider
2020 年 9 月 22 日
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
.
2 件のコメント
Star Strider
2020 年 9 月 22 日
My code runs without error and produces the correct result. The ‘NewSpeed’ (1x15) cell array of (1x5) double vectors was never in the original problem.
Indexing into it is straightforward cell array indexing:
SelectNewSpeed = NewSpeed([index{:}])
with:
Result = cell2mat(SelectNewSpeed) % Works Here Because The Vectors Are The Same Size
producing
Result =
3 3
4 4
5 5
2 2
1 1
Those two vectors (elements 12 and 14) are the same. The code retrieved them correctly, as can be demonstrated by altering one number from each of those vectors to demonstrate that in that event they’re different.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Operators and Elementary Operations についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!