Turning a sequence of operations into a function

3 vues (au cours des 30 derniers jours)
GEORGIOS BEKAS
GEORGIOS BEKAS le 18 Nov 2021
Modifié(e) : Jan le 18 Nov 2021
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?

Réponses (1)

Jan
Jan le 18 Nov 2021
Modifié(e) : Jan le 18 Nov 2021
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];

Catégories

En savoir plus sur MATLAB dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by