X,Y vector should be the same size

6 views (last 30 days)
Jovos
Jovos on 22 Feb 2016
Answered: Star Strider on 22 Feb 2016
Hi, I want to plot the data. But it keeps giving me errors. I wonder where it went wrong?
filename = input('Please enter the file name: ');
fid01 = fopen(filename,'r');
for i= 1:15
line = fgets(fid01);
end
x = zeros(1,0);
y = zeros(1,0);
for i = 16:66
line = fgets(fid01);
z = strread(line,'%s');
nyear = str2num(z{1});
for j = 2:13
dat = str2num(z{j});
if ( dat== -99.9900)
dat=NaN;
end
year = nyear + (j-1)/12 ;
x = [x, year];
y = [y ,dat];
fprintf('%f %f\n',x,y);
end
end
hold on
plot(x,y,'blue');
p0 = polyfit(x,y,0);
y0 = polyval(p0,x);
plot(x,y0,'red');
p1 = polyfit(x,y,1);
y1 = polyval(p1,x);
plot(x,y1,'green');
p2 = polyfit(x,y,2);
y2 = polyval(p2,x);
plot(x,y2,'yellow');

Answers (1)

Star Strider
Star Strider on 22 Feb 2016
This code reads the file, detects missing data and sets them to NaN, and then plots. I’m not certain what you want to do your regressions on, but it should be relatively straightforward from here:
fidi = fopen('Mauna Loa Atmospheric CO2.txt', 'r');
DC = textscan(fidi, repmat('%f',1,14), 'HeaderLines',15, 'CollectOutput',1);
fclose(fidi);
D = cell2mat(DC);
Fil_Len = size(D,1);
CO2_Mos = zeros(12*Fil_Len, 4); % Preallocate
for k1 = 1:size(D,1)
idx_rng = [1:12]+(12*(k1-1)); % Calculate Index Range
CO2_Mos(idx_rng,:) = [repmat(D(k1,1), 12, 1), [1:12]', ones(12,1), D(k1,2:13)']; % Create Date Vectors & Monthly CO2 Concentrations Matrix
end
D_DN = datenum(CO2_Mos(:,1:3)); % Convert Date Vectors To Date Numbers
Missing = CO2_Mos(:,4) == -99.99; % Detect Missing Values
CO2_Mos(Missing) = NaN; % Set Missing CO2 Values To ‘NaN’
D_DN(Missing) = NaN; % Set Corresponding Date Numbers To ‘NaN’
figure(1)
plot(D_DN, CO2_Mos(:,4))
grid
datetick('x', 'yyyy mm')
title('Mauna Loa, Hawaii Atmospheric CO_2 Concentrations, 1958-2008')
xlabel('Time')
ylabel('[CO_2] (ppmv)')
The plot is a bit frightening!
How it works
It uses the textscan function (obviously) to read the file into a cell array, then converts that to a double array, checks the sizes, and preallocates the ‘CO2_Mos’ array. It then loops through each line of the file, calculates a serial index range for that year, and creates a matrix of date vectors for each year, month, and the first day of the month, and appends the CO2 values for those months as the fourth column. After the loop, it searches out the missing data (given as -99.99), replacing them and the associated dates with NaN values. (You don’t have to do this, but it creates a nicer-looking plot.) Then it plots the data, using the datetick function to format the dates.
For renewable energy advocates like me, the necessity of that, seeing the plot, is self-explanatory! 350.org

Categories

Find more on Dates and Time 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!