Graphing from txt file? - Homework

2 次查看(过去 30 天)
I am not sure what is wrong with the script:
So the data looks like this:
World population
YEAR BC/AD POPULATION
10000 BC 1000000
8000 BC 5000000
6500 BC 5000000
5000 BC 5000000
I need to use the first column (year) as the x axis (as negative numbers if BC and positive is AD).
I need the third column to be the y axis in log scale (I am having trouble with this part too).
My script so far:
[fid, msg] = fopen('hw12_2.txt','w');
if fid==-1
fprintf(2,'FAILED TO OPEN FILE. %s\n', msg);
return;
end
% FIRST LINE OF DATA
title_str= fgetl(fid);
% SECOND LINE HAS LABELS
aline=fgetl(fid);
[x_str, ystr]=strtok(aline);
y_str = ystr(7:end);
hold on
line1 = fgetl(fid);
line2 = fgetl(fid);
y = fid(:,3);
x = fid(:,1);
plot(x,y);
% USE LABELS FROM ABOVE USING FIRST AND SECOND LINE
xlabel(x_str);
ylabel(y_str);
title(title_str);
hold off

采纳的回答

Umair Nadeem
Umair Nadeem 2013-11-17
编辑:Umair Nadeem 2013-11-17
I get it what you are trying to achieve. Here is the code I developed after a little modification of yours.
clear all;
clc;
[fid, msg] = fopen('hw12_2.txt','r');
if fid==-1
fprintf(2,'FAILED TO OPEN FILE. %s\n', msg);
return;
end
% FIRST LINE OF DATA
title_str= fgetl(fid);
% Initialize z and y axis arrays
xstr =[];
ystr =[];
aline = 1;
while aline ~= -1
% SECOND LINE HAS LABELS
aline=fgetl(fid);
if (aline ~= -1)
[x_str, y_str_temp] = strtok(aline);
[Dec, y_str] = strtok(y_str_temp);
x_str = str2double(x_str);
y_str = str2double(y_str);
% cmpr stores the result of comparison of both strings i.e. check
% whether it is equal to BC or not
cmpr = strcmp(Dec, 'BC');
if (cmpr == 1)
x_str = -1 * x_str;
end
xstr = [xstr x_str];
ystr = [ystr y_str];
end
end
% Convert the y-axis in log scale
ystr = log10(ystr);
bar(xstr,ystr);
% USE LABELS FROM ABOVE USING FIRST AND SECOND LINE
xlabel('Year');
ylabel('Population');
title(title_str);
It works perfectly fine and just like the way you want it, but you have to take care of one thing that the text file must not have any empty lines between the line with actual text, otherwise the compiler would take that the file has ended and it will return a -1. It should be like this
YEAR BC/AD POPULATION
10000 BC 1000000
8000 BC 5000000
6500 BC 5000000
5000 BC 5000000
This way it will work absolutely fine. Hope it helps
  7 个评论
Image Analyst
Image Analyst 2013-11-18
Looks like hw12_2.txt somehow didn't get attached. Try again. Make sure you click the "Attach file" button after you click the "Choose file" button.
Nora
Nora 2013-11-18
I found out the problem. Thank you!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 MATLAB Mobile Fundamentals 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by