如何在MATLAB中使用数组保存多个函数?

3

我是MATLAB的新手,不知道这是否可能,但是这就是我的问题... 我尝试使用plot函数在单个图形中打印多行。问题是,我希望能够通过更改变量来指定图形应显示多少行,例如:{这是我想做的伪代码}

 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

我知道上面的伪代码并不是完全符合MATLAB的语法,但我只想知道在MATLAB中是否可以实现这样的算法。

2个回答

2

以下是在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

以下是一些文档链接,您应该阅读以学习和理解上述代码:


1
你是否查阅过MATLAB手册?它写得非常好,有许多例子。复制这些示例脚本并粘贴到命令窗口中,看看会发生什么...

http://www.mathworks.com/help/techdoc/creating_plots/f9-53405.html

你可以编写脚本或使用他们的绘图工具: http://www.mathworks.com/help/techdoc/creating_plots/f9-47085.html

--- 脚本示例

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)

玩得开心。


问题:如果我只想在 x 等于 3 的时候绘制图形,那么我的 if 语句应该是 if( x == 3) 吗? - Y_Y
如果我理解正确的话(这里只是猜测),您希望仅绘制n==3吗?换句话说,您只想绘制第三行吗?如果是这种情况,是的 - 您可以添加:if (n==3); <plot the line>; end。 - Y.T.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接