Aggregating the same value data and finding the average
1 view (last 30 days)
Show older comments
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 Comments
Answers (1)
Image Analyst
on 19 Jan 2015
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 Comments
Image Analyst
on 19 Jan 2015
PArray does not get any values unless the value is within tolerance of the start value, so many go unassigned and remain zero.
See Also
Categories
Find more on MATLAB Mobile Fundamentals in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!