Accessing specific values in every matrix in a cell array
조회 수: 12 (최근 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!