How do you sum the number of boxes in this cell array?

조회 수: 2 (최근 30일)
Jason
Jason 2014년 10월 14일
답변: Mohammad Abouali 2014년 10월 14일
% create cell array of box types, number of boxes
% and box dimensions in mm
boxData = {'smallSquareBox', 14, [50, 50, 50], ...
'largeSquareBox', 9, [100, 100, 100], ...
'smallRectBox', 7, [40, 60, 30], ...
'largeRectBox', 2, [120, 260, 80]};
Write a MATLAB problem that will determine the total number of boxes. Hint: use iteration to extract the contents of the cell array corresponding to the numbers of each box type and sum the resulting numbers. The program should work for any cell array of data formatted like the boxData cell array, not just specific boxData cell array. I'm not sure how to do this if anyone could help me out I would really appreciate it!!
I tried this but it wont work...
for k = boxData(2:3:end)
nums = k{1,:};
totalboxes = sum(nums);
end
disp(totalboxes)

채택된 답변

Mohammad Abouali
Mohammad Abouali 2014년 10월 14일
Does this work:
sum(cell2mat(boxData(2:3:end)))

추가 답변 (1개)

SK
SK 2014년 10월 14일
You've got the cell referencing wrong. Try:
nums = [boxData{2:3:end}]; % Note the square brackets.
totalboxes = sum(nums);
disp(totalboxes)
(a:b:c) refers to the cells specified by the indices.
{a:b:c} refers to the list of cell contents specified by the indices.
[{a:b:c}] puts the list of contents into an array if they are all of the same type. (but [] is not necessary if the there is only one element in the list).

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by