Functions with 2 variables

1 Ansicht (letzte 30 Tage)
Jens Petit-jean
Jens Petit-jean am 17 Feb. 2021
Kommentiert: Walter Roberson am 21 Feb. 2021
How do you make a function (NOT an anonymous function) from this?
"Als" means "if"
Thanks in advance
  6 Kommentare
Walter Roberson
Walter Roberson am 17 Feb. 2021
k does not need to be an input for this function. The conditions have to do with x modulo 4: -2 <= mod(x,4) < 0 is the second condition, and 0 <= mod(x,4) < 2 is the first condition.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 17 Feb. 2021
format long g
mat2str(g(-9:.5:9))
ans = '[0 0.5 2 3.5 4 3.5 2 0.5 0 0.5 2 3.5 4 3.5 2 0.5 0 0.5 2 3.5 4 3.5 2 0.5 0 0.5 2 3.5 4 3.5 2 0.5 0 0.5 2 3.5 4]'
function output = g(x)
k = floor(x/4);
rm = x - 4*k;
mask = rm < 2;
output = zeros(size(x));
output(mask) = 4-2*(rm(mask) - 1).^2;
output(~mask) = 2*(rm(~mask) - 3).^2;
end
  7 Kommentare
Walter Roberson
Walter Roberson am 17 Feb. 2021
k is an element of integers.
For any given real finite x, there is exactly one integer k such that 4*k-2 <= x < 4*k+2. If you try to use any other k then both range tests will fail.
Once you know the k that makes the above true, then the two different conditions decide between halves, 4*k-2 <= x < 4*k, or 4*k <= x < 4*k+2
I coded in a slightly tricky way for the second condition: you may need some study to figure it out.
I could have coded a different way overall, finding k based on floor((x+2)/4) . If you do that, make sure you get the boundaries right.
Jens Petit-jean
Jens Petit-jean am 17 Feb. 2021
oooooh thanks I get it now, really appreciate the help!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Asayel Alazmi
Asayel Alazmi am 21 Feb. 2021
Write an mfile using for loop to output a all numbers from 1 to 4 with an increment of 0.2
  1 Kommentar
Walter Roberson
Walter Roberson am 21 Feb. 2021
No, I don't think doing that would help solve the question that the person posted.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Function Creation finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by