Dealing with Cells
A customer recently asked me this question at the MATLAB Virtual Conference.
Contents
Question about Summing Cell Rows
I was hoping you would cover cells some day. Here is a particular problem I was hoping to have a more elegant solutions for.
A is a cell that has String (say names) in the first column, Numbers (say scores in tests 1 and 2) in the next two columns. Assume that each cell has only one value. Is there an easier way to calculate, say the sum of the two test scores than a for loop?
Example
Let's make some sample data.
c(1:4,1) = {'Fred' 'Alice' 'Lucy' 'Tom'}; c(1:4,2) = { 90 80 55 102 }; c(1:4,3) = { 43 91 80 44 }
c = 'Fred' [ 90] [43] 'Alice' [ 80] [91] 'Lucy' [ 55] [80] 'Tom' [102] [44]
Answer
To sum the entries in a row for this cell array, I can simply turn the numeric values into a numeric array via comma-separated list notation, and then sum the rows. Let's see the pieces for clarity. Here's the comma-separated list.
c{:,2:3}
ans = 90 ans = 80 ans = 55 ans = 102 ans = 43 ans = 91 ans = 80 ans = 44
Now place the results into a vector.
vec = [c{:,2:3}]
vec = 90 80 55 102 43 91 80 44
Reshape the vector appropriately into a matrix.
array = reshape(vec,[],2)
array = 90 43 80 91 55 80 102 44
Now sum the results along the rows.
tot = sum(array,2)
tot = 133 171 135 146
Or, in one bigger statement, try this.
tot = sum(reshape([c{:,2:3}],[],2),2)
tot = 133 171 135 146
Cell Array Questions
Do you use cell arrays? Can you do what you want without undo contortions? Let me know here.
- 类别:
- Cell Arrays
评论
要发表评论,请点击 此处 登录到您的 MathWorks 帐户或创建一个新帐户。