How do I hold multiple functions in an array in MATLAB?
I am new to MATLAB so I don't even know if this is possible, but here it is... I am trying to print multiple lines in a single graph using the plot function. The problem is, I want to be able to specify how many lines the 开发者_如何学Pythongraph should display by simply changing a variable, for example: {This is the pseudo code to what I want to do}
number_of_lines = 4;
x = 0:0.5:5;
function_output[number_of_lines];
for n=0:number_of_lines
function_output[n] = sin(n + x);
end
for n=0:number_of_lines
plot(x,function_output[n]);
end
I know the above pseudo code isn't exactly MATLAB, but all I want to know if such algorithm is possible to do in MATLAB.
Here's one way to implement your example in MATLAB:
function_output = zeros(numel(x), number_of_lines); % Initialize a 2-D array
for n = 1:number_of_lines % MATLAB uses 1-based indexing
function_output(:, n) = sin(n + x).'; %' Compute a row vector, transpose
% it into a column vector, and
% place the data in a column of
% the 2-D array
end
plot(x, function_output); % This will plot one line per column of the array
And here are some documentation links you should read through to learn and understand the above code:
- Matrices and Arrays
- Matrix Indexing
- Arithmetic Operators
- The
plot
function
Have you looked through the MATLAB manual? -- it is quite well-written with many examples. Copy the example scripts and paste them onto the Command Window and see what happens...
http://www.mathworks.com/help/techdoc/creating_plots/f9-53405.html
You can either write a script or use their plotting tool: http://www.mathworks.com/help/techdoc/creating_plots/f9-47085.html
--- script example
number_of_lines = 4;
x = 0:0.5:5;
function_output=ones(number_of_lines,1)*nan;
figure;hold on;
for n=1:number_of_lines
function_output(n,1) = plot(x,sin(n+x),'color',[1-n/number_of_lines 0 n/number_of_lines]);
end
legend(function_output)
Have fun .
精彩评论