【问题标题】:IN MATLAB: How to plot a graph every 3 lines from a Text file?在 MATLAB 中:如何从文本文件中每 3 行绘制一个图形?
【发布时间】:2014-01-17 21:38:56
【问题描述】:

我有一个包含 2 列的大型文本文件,其中的值用逗号分隔。我正在尝试创建一个简单的程序,该程序允许使用连续每 3 行提取的数据绘制图表,直到到达文件末尾。

我的文件的前 9 行如下所示:

115,1.2
324,3.4
987,1.2
435,-2.3
234,1.4
278,1.3
768,3.4
345,-1.3
126,3.6

我一直在阅读,使用“Textread”我可以将我的数据写入多个输出,然后我可以使用“绘图”在图表上绘制先前生成的输出。我知道我需要一些循环来重复该过程并指示文件的结尾等。但我正在努力寻找这样做的方法:-(。

我只为我的文件的前 3 行绘制了一个图表(见下面的代码),但我需要重复这个过程直到文件结束。

[Codes,Values]=textread('MyData.txt','%3u %f',3,'delimiter',',','emptyvalue',NAN); %//Reads the first three rows of my file and stores the values in 2 variables 
figure
plot(Codes,Values) %//plots a graph with the variables obtained before
saveas(gcf,'Graph.pdf') %//Saves the created graph in a pdf format file.

如果有人可以帮助我,我将不胜感激。

【问题讨论】:

    标签: matlab file graph plot repeat


    【解决方案1】:

    我终于找到了办法。我在这里粘贴了允许我从我的文本文件中每三行绘制一个图表的代码。

    [Codes,Values]=textread('MyData.txt','%3u %f','delimiter',',','emptyvalue',NAN); %//Reads my text file and stores the values in 2 variables 
    
    nrows=1;
    conta=1;
    contb=3;
    contc=1;
    contd=3;
    nfig=1;
    
    while nrows<=size(Codes,1)
    
       if contb<=size(Codes,1)
    
          Codes1=Codes(conta:contb,1);
          Values1=Values(contc:contd,1);
          figure
          plot(Codes1,Values1) %//plots a graph with the selected rows.
          saveas(gcf,strcat('Graph', num2str(nfig),'.pdf')) %//Saves the created graph in a pdf format file.
       else
          Codes1=Codes(conta:contb,1);
          Values1=Values(contc:contd,1);
          figure
          plot(Codes1,Values1) %//plots a graph with the selected rows.
          saveas(gcf,strcat('Graph', num2str(nfig),'.pdf'))
       end
    
       nrows=nrows+3;
       conta=conta+3;
       contb=contb+3;
       contc=contc+3;
       contd=contd+3;
       nfig=nfig+1;
    end
    

    【讨论】:

      【解决方案2】:

      您提到它是一个大文本文件,但是加载整个文本文件然后简单地每隔三行采样一次会不会有问题,例如,如下:

      [Codes, Values] = textread('MyData.txt','%3u %f','delimiter',',','emptyvalue',NAN);
      
      rowstokeep = 1:3:length(Values) % every third line
      
      plot(Codes{rowstokeep}, Values{rowstokeep}); % plot just the rows you wanted
      

      【讨论】:

        猜你喜欢
        • 2013-12-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多