Reference multiple elements in a cell array

조회 수: 5 (최근 30일)
Andrew Bellocchio
Andrew Bellocchio 2017년 11월 30일
답변: Stephen23 2017년 12월 1일
Hi all, I am unsure on the best way to reference multiple elements in a cell array. Suppose I have 4 parts and each is a cell. All parts are contained within a larger cell array as:
Part01={'Exponential' 1/lambda_A 0 age1 0};
Part02={'Exponential' 1/lambda_B 0 age2 0};
Part03={'Exponential' 1/lambda_C 0 age3 0};
Part04={'Exponential' 1/lambda_D 0 age4 0};
Parts={Part01;Part02;Part03;Part04};
Each age# value is a single number. I want to create a single vector like this:
AgeVector=[age1, age2, age3, age4]
I can do so using:
PartAgeVector=[Parts{1}{4} Parts{2}{4} Parts{3}{4} Parts{4}{4}];
This seems awfully ugly and inefficient. The number of Parts will change with each use and I want to avoid manually coding like the last line of code. How may I most efficiently create a single vector.
Thank you! A.Bellocchio
  댓글 수: 2
Stephen23
Stephen23 2017년 12월 1일
"This seems awfully ugly and inefficient"
It is. If you simply put your numeric data into a numeric array then this entire problem goes away.
Andrew Bellocchio
Andrew Bellocchio 2017년 12월 1일
Agreed, but my part data is conveniently organized with both text and numbers. Using cell arrays is new to me. I was hoping to learn an easy way to pull data when the array has different types of cells.

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

채택된 답변

KSSV
KSSV 2017년 12월 1일
PartAgeVector = cell2mat(cellfun(@(x) x(1,4), Parts))
  댓글 수: 1
Andrew Bellocchio
Andrew Bellocchio 2017년 12월 1일
편집: Andrew Bellocchio 2017년 12월 1일
Yay, this works well. Thank you, KSSV. I can also build the PartAgeVector using a for loop such as:
no_parts=length(Parts);
for part=1:no_parts
PartAgeVector3(part)=Parts{part}{4};
end
Still, this is bulky. Is there a way to pull the data with indexing directly like we would with a pure matrix?

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

추가 답변 (1개)

Stephen23
Stephen23 2017년 12월 1일
This is trivial with a comma-separated list:
>> C = {1,11,111;2,22,222;3,33,333;4,44,444}
1 11 111
2 22 222
3 33 333
4 44 444
>> [C{:,3}]
ans =
111 222 333 444

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by