フィルターのクリア

How To Make Code Run Faster

1 回表示 (過去 30 日間)
Bailey Smith
Bailey Smith 2018 年 6 月 18 日
コメント済み: Bailey Smith 2018 年 6 月 19 日
What can I change about my code to make it run quicker/more efficiently? I would really appreciate it if things were listed one at a time, such as "change this one thing" or "change that one thing". I am trying to learn how to code more efficiently, but don't want to change my whole code, so changing one little thing here and there could really help me to learn this language better. Thank you!
clear; clc;
tic
x=0:pi/100000:pi;
y=sin(x);
n=1;
L=length(x);
while n<L
m(n,1)=x(n);
m(n,2)=(y(n+1)-y(n))/(x(n+1)-x(n));
n=n+1;
end
m(n,1)=x(n);
m(n,2)=NaN;
toc

採用された回答

Stephen23
Stephen23 2018 年 6 月 18 日
編集済み: Stephen23 2018 年 6 月 18 日
1. The most important change you could make would be to preallocate the matrix m:
2. You should also replace the while loop with a for loop, which is pretty easy as you know exactly how many iterations are required. In some low-level languages while loops are used very liberally, but in high-level MATLAB for loops are preferred (for simplicity, ease of debugging, etc).
3. The final step would be to realize that using a loop is an inefficient way to solve this problem anyway, and that using diff and rdivide would be simpler and faster.
  3 件のコメント
Stephen23
Stephen23 2018 年 6 月 18 日
L = numel(x);
m = zeros(L,2);
Bailey Smith
Bailey Smith 2018 年 6 月 19 日
Thank you so much for the help!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by