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

2 vues (au cours des 30 derniers jours)
Jason
Jason le 14 Oct 2014
% 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)

Réponse acceptée

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

Plus de réponses (1)

SK
SK le 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).

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by