Extract first and last row of each subarray in a cell array

조회 수: 7 (최근 30일)
JIAN-HONG YE ZHU
JIAN-HONG YE ZHU 2023년 4월 10일
댓글: Walter Roberson 2023년 4월 10일
Hello, if I have a 7×1 cell array, how could I extract the first and last row of each sub-array.
So if my cell looks like this:
I would like to end up with a matrix that looks like this (I put spaces so it is more clear what I want from each sub-array) :
50.0000 30.0000
50.4897 31.9177
61.0370 51.2245
61.5267 53.1422
61.5267 65.1422
60.6073 66.8252
58.5037 67.4803
54.2273 68.6080
52.1029 69.2125
51.0000 71.0000
I included the 7x1 cell array file.
Thanks.

채택된 답변

Paul
Paul 2023년 4월 10일
편집: Paul 2023년 4월 10일
I think this works even if the first and last row of a cell are identical.
load(websave('cellArray.mat','https://www.mathworks.com/matlabcentral/answers/uploaded_files/1350539/cellArray.mat'));
out = cellfun(@(x) x(1:max(end-1,1):end,:),group1,'UniformOutput',false)
out = 7×1 cell array
{[ 50 30]} {2×2 double } {2×2 double } {[60.6073 66.8252]} {2×2 double } {[52.1029 69.2125]} {[ 51 71]}
out = vertcat(out{:})
out = 10×2
50.0000 30.0000 50.4897 31.9177 61.0370 51.2245 61.5267 53.1422 61.5267 65.1422 60.6073 66.8252 58.5037 67.4803 54.2273 68.6080 52.1029 69.2125 51.0000 71.0000
  댓글 수: 1
Walter Roberson
Walter Roberson 2023년 4월 10일
By the way, @Paul the websave() work-around is no longer generally needed. If you use the attachment toolbar icon, then the second tab, "Link from this thread" allows you to select items that other people have attached in the Question, a makes them available for the Run facility (without duplicating them -- it makes links internally.)

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Walter Roberson
Walter Roberson 2023년 4월 10일
output = cellfun(@(C) C(unique([1, end]), :), YourCellArray, 'uniform', 0)
The unique() is there to prevent it from accidentally copying data when there happens to be only one row in a cell

the cyclist
the cyclist 2023년 4월 10일
I believe this does what you want.
load cellArray.mat
c = cellfun(@(x)unique(x([1 end],:),"row"),group1,"UniformOutput",false);
m = cell2mat(c)
m = 10×2
50.0000 30.0000 50.4897 31.9177 61.0370 51.2245 61.5267 53.1422 61.5267 65.1422 60.6073 66.8252 54.2273 68.6080 58.5037 67.4803 52.1029 69.2125 51.0000 71.0000
The cells that have one row make this a bit tricky. The first and last row of a one-row are the same, but it looks like you don't want it listed twice. So, I use "unique" to get only one of them. But, this algorithm will fail if the first and last row of a multi-row array are identical.

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

태그

제품


릴리스

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by