Turning a sequence of operations into a function

1 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by