Find average values in a table

I have a table that is 5x7 (see below), I want MATLAB to choose the first cell from the first row (23.869) and then go to the second row and find the closest number to the number in the first raw, which is 25.861, and then go the third row and find the closest number to the number in the first row and so on to the row number 5 and then I want MATLAB to calculate the average of those numbers. Then I want to repeat the same process on the second cell, third cell, ... seventh cell.
How can I do that, any idea?
23.869 111.52 348.59 241.02 167.31 539.84 802.81
111.52 25.861 350.59 241.02 161.33 537.85 0
27.37 350.24 113.41 240.78 181.08 537.33 808
349.27 25.908 237.49 111.74 175.61 539.59 325.32
25.787 113.44 350.51 232.97 537.63 804.73 0

2 个评论

Write your expected output explicitly so that it would be better to understand.
The expected output for the first value in the table
23.869 25.861 27.37 25.9080 25.7870
and then MATLAB use "mean" function to calculate the mean of this row and then repeat the process for the second value in the table, and so on to the seventh value

请先登录,再进行评论。

 采纳的回答

a = randi(10,5,7); % let a be your matrix
closest_all =zeros(1,7);
for i = 1:size(a,2) %first row values,
num = a(1,i); % this will be your 23.869, 111.52, etc...
closest = zeros(1,4);
for j = 2:size(a,1) % from the second row to 5th
row = a(j,:);
[min_val idx] = min(abs(row - num)); %all row elements minus 23.869
closest(j-1) = row(idx); %store the closest value to 23.689, then 111.52,etc...
end
closest_all(i) = mean(closest); %find the averages of the 4 values.
end
%closests_all will be a 1x7 vector containing all those averages

4 个评论

Hi Kevin,
Thank you for your anwser. 
The problem with the code above is that it consider the first value is zero (23.869 is zero) and the code takes the mean of five numbers.
The code is doing this
0 25.861 27.37 25.9080 25.7870
and then it calculates the mean value of this row, which is not correct because the first number is not zero, it is 23.869
Sorry, I missed an index.
I changed it to
closest(j-1) = row(idx); %store the closest value to 23.689, then 111.52,etc...
it was just closests(j) so it was skipping the first index.
I have editted my answer, it should work now. Your answer should be :
closest_all =
26.2315 112.5275 350.1525 238.0650 157.8650 538.1000 672.5425
It works now, thank you very much
you're welcome! :)

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by