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

2 views (last 30 days)
% 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)

Accepted Answer

Mohammad Abouali
Mohammad Abouali on 14 Oct 2014
Does this work:
sum(cell2mat(boxData(2:3:end)))

More Answers (1)

SK
SK on 14 Oct 2014
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).

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!