Info

此问题已关闭。 请重新打开它进行编辑或回答。

Cleaner way to calculate mean

1 次查看(过去 30 天)
Jasmine Karim
Jasmine Karim 2018-8-31
关闭: MATLAB Answer Bot 2021-8-20
I have an array with 18 columns - each column is a cell array itself of varying lengths. I am trying to perform basic calculations with this, finding the mean, but all the cells are divided by different cells. So cell 4/cell 1. Cell 6/3
A = [21x8 cell 46x8 cell 13x8 cell 11x8 cell 27x8 cell 4x8 cell 10x8 cell 77x8 cell 173x8 cell]
I was going to write something similar to what is below, but that would require a lot of repeating lines. Is there a cleaner/more efficient way to write this?
for k = 1:size(A)
for h = 1:length(A)
B = length(A{k,h});
avg.A = (B(a,6)/C(a,3))*100;
avg.B = (B(a,5)/C(a,2))*100;
avg.C = (B(a,4)/C(a,1))*100;
avg.D = (B(a,9)/C(a,3))*100;
avg.E = (B(a,8)/C(a,2))*100;
avg.F = (B(a,7)/C(a,1))*100;
end
end
...and so forth. As you can see, this will produce 18 different lines of code which looks terrible.
  1 个评论
dpb
dpb 2018-8-31
Well, no, "I don't see", at least completely... :)
What is a in
(B(a,6)/C(a,3))*100;
(B(a,5)/C(a,2))*100;
(B(a,4)/C(a,1))*100;
(B(a,9)/C(a,3))*100;
(B(a,8)/C(a,2))*100;
(B(a,7)/C(a,1))*100;
?
Since there's an apparent symmetry in the second subscripts as paired with each other, what's the general rule that determines those?
B=length(A{k,h});
will be a constant so how can it have subscript (a,N).
What is the actual arithmetic computation you're trying to accomplish?
Show us a (small) sample A and then the desired output from it and how got it from the input. It shouldn't take but a small subset of the real problem with small(ish) arrays to illustrate.

回答(1 个)

Image Analyst
Image Analyst 2018-8-31
I have no idea what B, C, and "a" are, but this will get you the mean of all cells of A
for k = 1 : length(A)
thisCellsContents = A{k}; % Extract double array.
meansOfA(k) = mean(thisCellsContents(:));
end
You could probably do it more compactly, though more cryptically, with cellfun().

此问题已关闭。

Community Treasure Hunt

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

Start Hunting!

Translated by