3

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 graph 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.

2 Answers 2

2

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:

Sign up to request clarification or add additional context in comments.

Comments

1

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 .

2 Comments

Question: What if I want to plot only when x is 3. Should by if statement be if( x == 3) ?
If I understood you correctly (I'm guessing here), you wish to plot only the n==3 ? In other words, you wish to plot only the 3rd line? If that is the case, yes - you can add: if (n==3); <plot the line>; end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.