Assigning legend in Matlab for-loop
I tried to give a legend in a loop, but it overwrites the previously written legend as it can be inserted either in an if statement or in a for loop. Confused
clear;
vin=10
for m=1:1:14;
vin=vin+10
for i=1:1:27
Wa_Ac = PVinv.CoreSizeModel();
PVinv.CoreSelect(Wa_Ac,i);
loss_ind_core= PVinv.InductorLossModel(PVinv.m_L_Selected);
if(i==1)
p=plot(vin,loss_ind_core,'--gs');
hold on
end
if(i==2)
p=plot(vin,loss_ind_core,'--rs');
end %...till i=27
legend(obj.m_Core_List(i).name);
xlim([10e3 90e3])
set(gca,'XTickLabel',{'10';'20';'30';'40';'50';'60';'70';'80';'90'})
grid on
xlabel('Vin');
ylabel('Power loss');
end
end
Called function
function obj = CoreSelect(obj, WaAc)
obj.m_Core_Available= obj.m_Core_List(i);
obj.m_L_Selected.m_Core = obj.m_Core_Available;
end
source to share
Create a cell array to store legend names. Before the loop, for
define something like
legend_names = cell(1,27 * 14);
Then, during the loop, fill the cell in:
legend_names{27*(m-1)+i} = obj.m_Core_List(i).name;
Then end
install the legend:
legend(legend_names);
I may have misunderstood the indices ( m
vs i
) and how they relate to names, but the point is, you can pass an array of cells to the legend function to create the legend in one go.
Example:
>> legend_names=cell(1,2);
>> legend_names{1} = 'str';
>> legend_names{2} = 'str2';
>> plot(0:4,0:4)
>> hold on
>> plot(1:5,0:4)
>> legend(legend_names)
which will give
source to share
Instead of collecting the legend line, you can simply set DisplayName
-property in your graphical commands. Alternatively, you can collect the arguments linespec
in a cell array to avoid code duplication, i.e.
linespec = {'--gs','--rs',... %# etc
(...)
for i=1:1:27
Wa_Ac = PVinv.CoreSizeModel();
PVinv.CoreSelect(Wa_Ac,i);
loss_ind_core= PVinv.InductorLossModel(PVinv.m_L_Selected);
p=plot(vin,loss_ind_core,linespec{i},'DisplayName',obj.m_Core_List(i).name);
end
legend('show')
source to share