フィルターのクリア

Turning a sequence of operations into a function

6 ビュー (過去 30 日間)
GEORGIOS BEKAS
GEORGIOS BEKAS 2021 年 11 月 18 日
編集済み: Jan 2021 年 11 月 18 日
I have a sequence of operations that attempts to calculate, whether there is an increase or a decrease in the next step, in comparison with the previous element of a matrix f:
f = [5 6 8 1 2 10 1 0 9 4 6 4]
f1 = [0]
k = 2
for i = 1:length(f)-1
if f(i+1) > f(i)
f1(k) = 1
else
f1(k) = 0
end
k = k+1
end
The code gives correct results.
How can I generalize the code into a function?

回答 (1 件)

Jan
Jan 2021 年 11 月 18 日
編集済み: Jan 2021 年 11 月 18 日
Start with simplifying the code:
  • k is i+1 in all cases, so omit k and use i+1.
  • Pre-allocate f1 by zeros() to avoid n iterative growing.
  • This is equivalent:
% Version 1:
if condition
a(k) = 1;
else
a(k) = 0;
end
% Version 2:
a(k) = double(condition);
If a is preallocated as double, the casting by double() can be omitted.
f = [5 6 8 1 2 10 1 0 9 4 6 4];
f1 = zeros(size(f));
for i = 1:length(f)-1
f1(i+1) = f(i+1) > f(i);
end
To convert this into a function:
f = [5 6 8 1 2 10 1 0 9 4 6 4];
f1 = compareWithNext(f)
function f1 = compareWithNext(f)
f1 = zeros(size(f));
for i = 1:length(f)-1
f1(i+1) = f(i+1) > f(i);
end
end
Shorter versions:
f1 = [0, f(2:end) > f(1:end-1)]
% Or even simpler:
f1 = [0, diff(f) > 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