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
per isakson
2015년 1월 19일
"I have attached the test file I use too."   No file attached, I guess you overlooked the Attach File button
Image Analyst
2015년 1월 19일
And why didn't you attach test1.csv so we could try your code????
blackhawk
2015년 1월 19일
답변 (1개)
Image Analyst
2015년 1월 19일
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
blackhawk
2015년 1월 19일
Image Analyst
2015년 1월 19일
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!