【问题标题】:Subplot and legend each graph in a for loop子图和图例 for 循环中的每个图
【发布时间】:2017-08-21 03:18:39
【问题描述】:

我正在尝试使用 for 循环编写一个 matlab 脚本,我想制作一个 4*2 的子图。

我尝试在每个图表中使用legend 函数,但是遇到了一个问题。我打算每个图都使用legend('Motor1+i') 作为图例,但所有图都具有相同的名称Motor1+i

我想要Motor1Motor2Motor3,...

g_wPWMOut=[g_wPWMOut0 g_wPWMOut1 g_wPWMOut2 g_wPWMOut3 g_wPWMOut4 ...
              g_wPWMOut5 g_wPWMOut6 g_wPWMOut7];

figure
for i=0:1:7;
   subplot(421+i)
   plot(FCCTime, g_wPWMOut(:,(1+i)))
   grid on
   legend('Motor1+i')
   ymax = max(g_wPWMOut(:,(1+i)));
   ymin = min(g_wPWMOut(:,(1+i)));
   xmax = max(FCCTime);
   xmin = min(FCCTime);
   axis([xmin-((xmax-xmin)*0.05) xmax+((xmax-xmin)*0.05) ...
   ymin-((ymax-ymin)*0.05) ymax+((ymax-ymin)*0.05)])
end

【问题讨论】:

    标签: matlab for-loop legend subplot


    【解决方案1】:

    首先,我想警告您,不建议使用i 作为变量,因为它被用作复数虚数单位。以ii 为例。

    那么,你误解了subplot的用法。您将 421+i 作为参数,但在您的情况下,它需要 3 个参数。你应该给4,2,1+i

    最后,您可以使用num2str,将ii 转换为字符串,再与strcat 结合使用Motorii 创建一个新字符串。

    for ii = 0:7
        subplot(4,2,1+ii);
        plot(FCCTime, g_wPWMOut(:,(1+ii)))
        legend(strcat('Motor', num2str(1+ii)))
    end
    

    你会得到如下结果:

    【讨论】:

      【解决方案2】:

      我没有测试,但是试试:

      mylegend = 'Motor';
      mylegend = [mylegend num2str(i)];
      legend(mylegend);
      

      【讨论】:

        猜你喜欢
        • 2015-10-10
        • 2019-09-04
        • 2023-03-19
        • 1970-01-01
        • 2016-03-16
        • 1970-01-01
        • 1970-01-01
        • 2021-03-08
        相关资源
        最近更新 更多