Turning a sequence of operations into a function

조회 수: 3 (최근 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 CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by