Accessing specific values in every matrix in a cell array
32 views (last 30 days)
I am using the 2021a release of Matlab if that makes a difference.
Lets say I have a cell array that contains N rows and M columns and each cell entry contains a 1x3 matrix of cartesian coordinates where the z values are in the third position of each matrix. I want to get all the z-values in each cell and put them into a matrix without using loops. I was wondering if there is a prewritten function that pulls out an entry or range of entries inside every matrix in every cell.
I think the equivalent in python would be something like:
MatrixofValues = MyCell[:,:]
Matt J on 3 Jul 2021
Edited: Matt J on 3 Jul 2021
I want to get all the z-values in each cell and put them into a matrix without using loops.
Even with built-in Matlab functions, cell arrays are always processed with the equivalent of an MCoded for-loop. There's no improving upon the efficiency of a for-loop when you're working with cells.That's why you may want to consider storing your data instead as an NxMx3 numeric array.
However, you can avoid the syntax of a for-loop by doing:
MyCell=reshape( num2cell(rand(20,3),2) ,5,4) %Example input
More Answers (2)
dpb on 3 Jul 2021
Edited: dpb on 3 Jul 2021
Unfortunately, MATLAB can't do partial array combo addressing -- best I can think of here creates the array xyz as an intermediary and then selects the z column -- which, if the data are as you describe, there's no advantage to having it as a cell array that I see (at least in MATLAB; I "know nuthink'!" about Python for why one would do so there...
If you just store xyz from the git-go, however, the coordinates are/will be directly available by straight indexing and you likely could do without creating the specific arrays at all.