AnyCompiler

Vectors Ke Saath Apne Functions Likhna

vectorized-operations se aage har cheez ek habit ki taraf build ho rahi hai: jab aap apna khud ka function likhte ho, usually koi reason nahi hota ki uski body apne input par bhi loop kare. Agar x ek vector hai, (x - min(x)) / (max(x) - min(x)) ek single vectorized expression hai jo, poore vector ke saath ek baar call hone par, normalized results ka ek poora vector produce karta hai — har call mein ek number compute nahi karta.

normalize <- function(x) {
  (x - min(x)) / (max(x) - min(x))
}
print(normalize(c(10, 20, 30, 40, 50)))
Output
[1] 0.00 0.25 0.50 0.75 1.00

normalize() exactly ek baar call hua, poore five-element vector ke saath uske single argument ki tarah — min(x) aur max(x) dono poore vector par ek ek baar chale, aur final subtraction aur division automatically element-wise chale, wahi tareeka jaise x + y bahut peeche vectorized-operations lesson mein hua tha. Result ek five-element vector hai jahan smallest input 0 ban gaya, largest 1 ban gaya, aur baaki sab beech mein proportionally scale ho gaya — sab kuch bina kabhi for ya kisi loop index likhe. Aage: closing thoughts — ek recap, aur aage kahan jaana hai.

Practice exercise

Ek function cube <- function(x) likho jo poore vector ke liye ek saath x^3 return kare, bina uske andar kisi loop ke. Ise c(1, 2, 3) ke saath call karo aur result print karo.