【问题标题】:How do I plot a graph through an indexed time in matlab?如何在matlab中通过索引时间绘制图表?
【发布时间】:2021-03-25 07:28:25
【问题描述】:

我有一个文本文件,我必须从中检索数据并绘制一个看起来像这样的图表。我想绘制一个图表,机器通过该图表具有 status="on"。我试图找到机器处于开启状态的索引。

我做了什么:

fid=fopen('power.txt');
line=fgetl(fid);
data=textscan(fid,'%d %f %s');
fclose(fid);

time=data{1};
power=data{2};
status=data{3};
status_on=strcmp(data{3},'on');

indices=find(status_on==0);
start_indices=indices+1;
%adding the first index where the status is on
start_indices=[1; start_indices];
%removing the last element as the last index will always have the value off
start_indices(end)=[];
end_indices=indices-1;

%Plotting Graph
plot(time,power,'-r');
xlabel('Time (s)');
ylabel('Power (W)');
title('Sonications over time');

这个图表只是给了我一个简单的情节,但我需要让我的图表看起来像这样。另外我一直在搜索标记的使用,是否需要编写特定的代码来获取这些标记或者是否有默认的 Matlab 函数?

【问题讨论】:

  • 显然当status 的幂为OFF 时,第二列(power)显示-1,所以在第二列中查找该值,所有不是-1 的都是然后ON.
  • 这是一个很好的观点。但是我需要我的图表在它关闭的时候是空白的,并且只有在我需要帮助的时候才会有一条线。
  • 您可以使用循环并通过另一个调用 plot 添加标记,并在使用 hold on 添加新绘图时保留当前绘图。

标签: matlab plot indexing time graph


【解决方案1】:

将不被绘制的值设置为NaN

您可以将与处于“关闭”状态的机器对应的索引填充到NaN(不是数字),并且在绘图时这些将被忽略。使用islocalmin()islocalmax() 函数查找局部最大值和最小值将允许根据索引绘制标记。

fid=fopen('power.txt');
line=fgetl(fid);
data=textscan(fid,'%d %f %s');
fclose(fid);

time=data{1};
power=data{2};
status=data{3};
status_on=strcmp(data{3},'on');

Off_Status = find(status == "off");
power(Off_Status) = "NaN";

Local_Minimum_Indices = islocalmin(power);
Local_Minimum_Indices(end-1) = 1;
Local_Maximum_Indices = islocalmax(power);
Local_Maximum_Indices(1) = 1;

%Plotting Graph
clf;
plot(time,power,'-r');
hold on
plot(time(Local_Maximum_Indices),power(Local_Maximum_Indices),'x','MarkerSize',10,'color','b');
plot(time(Local_Minimum_Indices),power(Local_Minimum_Indices),'s','MarkerSize',10,'color','g');

xlabel('Time (s)');
ylabel('Power (W)');
title('Sonications over time');
ylim([0 max(power)+2]);

使用 MATLAB R2019b 运行

【讨论】:

  • 谢谢,您的代码有效。我可以添加任何默认函数来获取这些特定点中的特定标记吗?
  • 几乎通过使用islocalmin()islocalmax() 函数,您可以找到需要绘制标记的索引。我编辑了我的答案以适应这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多