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

2 次查看(过去 30 天)
% 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