Aggregating the same value data and finding the average

I read data from a CSV file. The file contains data values which has the same value in the first column. I use the following code to read the vales. However the if condition is not working after three iterations.
%start = 20659200000.000000;
Array=csvread('test1.csv');
format long g;
start = 20659200000.000000;
%start = 2.06592e+10
d = size(Array, 1);
dd = 0;
i = 1;
while i < d
tmp = Array(i,1);
% start = 20659200000.000400;
if eq(tmp , start)
start = start + 0.000100;
dd = dd + 1;
PArray(i,1)= Array(i,1);
PArray(i,2)= Array(i,2);
end
i = i + 1;
end
I have attached the test file I use too. Can anybody sport what is the bug in the if condition?
Thanks in advance

4 个评论

"I have attached the test file I use too." &nbsp No file attached, I guess you overlooked the Attach File button
And why didn't you attach test1.csv so we could try your code????
Yes like per isakson mentioned I have overlooked the Attach File button. It is now attached. Sorry this is the first time I user this forum
I tried this too, still it won't iterate more than 3
value = tmp - start; if eq(value,0)

请先登录,再进行评论。

回答(1 个)

Tons of errors in the code, the main error being that you're comparing floating point numbers for equality and you're not following the FAQ: http://matlab.wikia.com/wiki/FAQ#Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero.3F Attached is the fixed code:
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 20;
Array=csvread('test1.csv');
start = 20659200000.000000;
tolerance = 0.01;
rows = size(Array, 1)
equalityCount = 0;
for row = 1 : rows;
tmp = Array(row,1);
fprintf('In row #%d of %d, column 1 = %f\n', row, rows, tmp);
if abs(tmp - start) < tolerance
start = start + 0.000100;
equalityCount = equalityCount + 1;
PArray(row,1)= Array(row,1);
PArray(row,2)= Array(row,2);
fprintf('^^^ Row %d above has equality ^^^\n', row);
end
end
fprintf('EqualityCount = %d\n = %.1f%%of the rows.\n', equalityCount, 100*equalityCount/rows);
msgbox('Done with demo');
It could be better and more robust, but it at least works now. Adjust the tolerance to what you want/need.

2 个评论

Thank you Image Analyst for the floating point number pointer and fixing the issues in the code. Your code works, however looking at the PArray there are many zero values. What could be the reason? Finally I want to plot the PArray.
plot(PArray(:, 1), PArray(:, 2));
PArray does not get any values unless the value is within tolerance of the start value, so many go unassigned and remain zero.

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 COM Component Integration 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by