如何提高运算速度?
使用数组进行运算!避免for循环。
python中结果相反,可参见https://blog.csdn.net/qq_43328166/article/details/108285468
示例:
计算一个分段函数f(x)= x² , x>1; 1 , -1<x<=1;3+2x , x<=-1
对比计算时间:①for循环计算、②矩阵进行计算、
脚本代码:
%%使用数组(一维、多维)计算,提高计算速度,避免for循环一个个计算元素。
%计算分段函数(piecewise function)f(x)= x² , x>1
% 1 , -1<x<=1
% 3+2x , x<=-1
x_array = [-10:0.01:10] %定义一个数组(列表),作为自变量
%调用函数
y1 = piecewise_function1(x_array)
y2 = piecewise_function2(x_array)
函数文件1:
function [y_arr]=piecewise_function1(x_arr) % 输入参数为数组x,输出也是数组y
n = length(x_arr)