필터 지우기
필터 지우기

Graphing from txt file? - Homework

조회 수: 4 (최근 30일)
Nora
Nora 2013년 11월 17일
댓글: Nora 2013년 11월 18일
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에서 Ordinary Differential Equations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by