MATLAB: Displaying names of multiple variables in a plot

MATLAB

I have 9 variables, which I am plotting over time and would like to dsiplay it in the line graph(plot). How do I do it? plot(dates, assetP); % legend('y=IEI', 'y=IEF', 'y=SHY', 'y=TLH','y=TLT', 'y=TIP', 'y=AGZ', 'y=CIU',… % 'y=HYG' ,'Location','southwest') hold on; plot(dates, benchmarkP, 'LineWidth', 3, 'Color', 'k'); hold off; xlabel('Date'); ylabel('Normalized Price'); title('Normalized Asset Prices and Benchmark'); datetick('x'); grid on;

Best Answer

Let us assume that you have following variables created in your workspace:
     >> v1 = rand(10,1);
     >> v2 = rand(10,1)+1;
     >> v3 = rand(10,1)+2;
     >> v4 = rand(10,1)+3;
     >> v5 = rand(10,1)+4;
     >> v6 = rand(10,1)+5;
     >> v7 = rand(10,1)+6;
     >> v8 = rand(10,1)+7;
     >> v9 = rand(10,1)+8;
1. You can concatenate all the variables into a matrix and then you can plot them as you iterate over matrix of variables using "for" loop with "hold on" command. To accomplish that you can execute following code:
     >> variables = [v1,v2,v3,v4,v5,v6,v7,v8,v9]; % This creates (10-by-9) matrix containing variables as individual columns. All the variables should have same number of values else MATLAB will throw an error.
     >> for i = 1:9
     >> plot(dates, variables(:,i)); % Variables are plotted column by column.
     >> hold on;
     >> end
     >> varNames = {'y = IEI','y = IEF','y = SHY','y = TLH','y = TLT','y = TIP','y = AGZ','y = CIU','y = HYG'}; % Create a cell array of strings for legend
     >> legend(varNames, 'Location', 'SouthWest'); % Provide the cell array as an argument to "legend" function. Number of entries in cell array should be same as number of variables.
     >> xlabel('Date');
     >> ylabel('Normalized Price');
     >> title('Normalized Asset Prices and Benchmark');
     >> datetick('x');
     >> grid on;
     >> hold off;
2. You can concatenate all the variables into a matrix and provide that matrix as input to the plot function which will plot the data for you. You do not have to use "hold on" command in this approach. To accomplish this you can execute:
     >> variables = [v1,v2,v3,v4,v5,v6,v7,v8,v9]; % This creates (10-by-9) matrix containing variables as individual columns. All the variables should have same number of values else MATLAB will throw an error.
     >> plot(dates,variables); % Variables are plotted column by column.
     >> varNames = {'y = IEI','y = IEF','y = SHY','y = TLH','y = TLT','y = TIP','y = AGZ','y = CIU','y = HYG'}; % Create a cell array of strings for legend
     >> legend(varNames, 'Location', 'SouthWest'); % Provide the cell array as an argument to "legend" function. Number of entries in cell array should be same as number of variables.
     >> xlabel('Date');
     >> ylabel('Normalized Price');
     >> title('Normalized Asset Prices and Benchmark');
     >> datetick('x');
     >> grid on;