Accessing specific values in every matrix in a cell array
17 ビュー (過去 30 日間)
古いコメントを表示
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[:,:][2]
0 件のコメント
採用された回答
Matt J
2021 年 7 月 3 日
編集済み: Matt J
2021 年 7 月 3 日
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
Q=vertcat(MyCell{:});
Matrix=reshape(Q(:,3),size(MyCell))
その他の回答 (2 件)
Peter O
2021 年 7 月 3 日
Sure, use cellfun:
A = {[1,2,3],[4,5,6],[7,8,9];[10,11,12],[13,14,15],[16,17,18]};
B = cellfun(@(x) x(3), A)
disp(B)
0 件のコメント
dpb
2021 年 7 月 3 日
編集済み: dpb
2021 年 7 月 3 日
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...
xyz=cell2mat(C);
z=xyz(:,3:3:end);
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.
1 件のコメント
dpb
2021 年 7 月 3 日
NB: The above produces an Nx(3M) array; another alternative would be as Matt J suggests, store by planes in 3D array.
While the cell array is compact at the top level cell arrays have two disadvantages --
- Overhead memory -- there's an extra "bunch o' stuff" needed to address the cell arrays that is added memory, and
- The dereferencing of the cell array is more complicated syntax and may require temporaries.
In general unless the data are of disparate types or sizes, it's better/more efficient to use native arrays.
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!