MATLABMATLAB · Chapterبەش 6 · Lectureوانە 6.1

Function Files and Anonymous Functionsفایلەکانی کردار و کردارە بێناوەکان

Write your own MATLAB functions: the function file and its header, the file-name rule, several inputs and outputs, nargin defaults and return, the function's private workspace (and why global is a bad idea), where functions may live in MATLAB and Octave, anonymous functions and function handles passed to fplot, fzero and integral, why to avoid eval, and timing code with tic and toc.

MATLABـی خۆت بنووسە: و ، یاسای ناوی ، چەند و ، بە nargin و return، تایبەتی (و بۆچی global بیرۆکەیەکی خراپە)، لە MATLAB و Octaveـدا لە کوێ دەژین، و کە دەدرێن بە fplot، fzero و integral، بۆچی خۆت لە eval بپارێزیت و کاتپێوانی کۆد بە tic و toc.

17 min read18 خولەک خوێندنەوە · 17 stepsهەنگاو

What you will learnچی فێر دەبیت

  • Write a function file with a correct header, save it under the function's name, and call it from the Command Window and from scripts.
  • Return several outputs, give defaults with nargin, and leave early with return.
  • Explain the difference between a script's shared Workspace and a function's private workspace.
  • Write anonymous functions with element-wise operators and pass function handles to fplot, fzero and integral.
  • Time code with tic and toc and know why eval, global and clock are avoided today.
  • بە دروست بنووسیت، بە ناوی پاشەکەوتی بکەیت و لە ⁦Command Window⁩ و بانگی بکەیت.
  • چەند بگەڕێنیتەوە، بە nargin بدەیت و بە return زوو دەربچیت.
  • جیاوازیی نێوان هاوبەشی و تایبەتی ڕوون بکەیتەوە.
  • بە بنووسیت و بدەیت بە fplot، fzero و integral.
  • کاتی کۆد بە tic و toc بپێویت و بزانیت بۆچی ئەمڕۆ خۆ لە eval، global و clock دەپارێزرێت.

Why write your own functions?بۆچی کردارەکانی خۆت بنووسیت؟

You have used MATLAB's from the start: sqrt(49), sum(v), factorial(5) (calling a function). You give a value, a result comes back, and you never see the code inside. A gives you the same thing for your own calculations. Three reasons to write one:

لە سەرەتاوە MATLABـت بەکار هێناوە: sqrt(49)، sum(v)، factorial(5) (بانگکردنی کردارێک). دەدەیت، ئەنجامێک دەگەڕێتەوە و هەرگیز کۆدی ناوەوەی نابینیت. هەمان شت بۆ هەژمارەکانی خۆت دەدات. سێ هۆکار بۆ نووسینی:

  • Reuse. Write the area formula once and call it a hundred times, from the Command Window, from scripts and from other functions.
  • Testing small pieces. A short function with clear inputs and outputs is easy to check by itself before a big program uses it.
  • A name for a job. x = quad_roots(1, -3, 2) says what happens; twenty lines of formula do not.
  • دووبارە بەکارهێنانەوە. فۆرموولەی ڕووبەر یەک جار بنووسە و سەد جار بانگی بکە، لە ⁦Command Window⁩، لە و لە ترەوە.
  • تاقیکردنەوەی پارچەی بچووک. کورت بە و ڕوون بە ئاسانی بە تەنها دەپشکنرێت پێش ئەوەی گەورە بەکاری بهێنێت.
  • ناوێک بۆ کارێک. x = quad_roots(1, -3, 2) دەڵێت چی ڕوو دەدات؛ بیست دێڕ فۆرموولە نایڵێت.
Quick checkپشکنینی خێراWhich of these is not a reason to write your own function?کامەیان هۆکار نییە بۆ نووسینی خۆت؟

Why write your own functions?بۆچی کردارەکانی خۆت بنووسیت؟

Functions in mathematics and in MATLABنەخشە لە بیرکاریدا و کردار لە MATLABـدا

In mathematics a function is a rule that gives one output for each input; a programming function is a named block of code and may also print, read input or use random numbers. Functions in mathematics and in programs compares the two. The course's Kurdish guide says that numerical methods in MATLAB are written as function files — this lesson teaches how, and every file here also runs in GNU Octave (free) and in the free version of MATLAB Online.

لە بیرکاریدا یاسایەکە کە بۆ هەر یەک دەدات؛ بلۆکێکی ناونراوی کۆدە و دەشێت چاپ بکات، بخوێنێتەوە یان بەکار بهێنێت. نەخشە لە بیرکاریدا و کردار لە بەرنامەکاندا هەردووکیان بەراورد دەکات. ڕێبەرە کوردییەکەی کۆرسەکە دەڵێت لە MATLABـدا وەک دەنووسرێن — ئەم وانەیە چۆنییەتییەکەی فێر دەکات و هەموو ئێرە لە ⁦GNU Octave⁩ (بەخۆڕایی) و وەشانی بەخۆڕایی ⁦MATLAB Online⁩ـیشدا کار دەکەن.

The post office counterپەنجەرەی پۆستەخانە

At the post office you hand a parcel and an address through the window, and a receipt comes back. You do not walk behind the counter or move their shelves. A function is that counter: inputs go in through the window, outputs come back, and the work inside stays inside.

لە پۆستەخانە پاکەتێک و ناونیشانێک لە پەنجەرەکەوە دەدەیت و پسوولەیەک دەگەڕێتەوە. ناچیتە پشت مێزەکە و ڕەفەکانیان ناجوڵێنیت. ئەو پەنجەرەیە: لە پەنجەرەکەوە دەچنە ژوورەوە، دەگەڕێنەوە و کاری ناوەوە لە ناوەوە دەمێنێتەوە.

Where the analogy stops workingسنووری ئەم نموونەیە

A post office remembers your parcel after you leave. A MATLAB function forgets its own variables as soon as it finishes; the next call starts fresh.

پۆستەخانە دوای ڕۆیشتنت پاکەتەکەت لە بیر دەمێنێت. MATLAB هەر کە تەواو بوو خۆی لە بیر دەکات؛ بانگکردنی داهاتوو لە سەرەتاوە دەست پێدەکات.

Quick checkپشکنینی خێراWhat can a MATLAB function do that a function in mathematics does not? MATLAB چی دەتوانێت بکات کە لە بیرکاریدا نایکات؟

A function fileفایلی کردار

A function lives in its own .m file. The first line is the : the keyword function, the output, =, the function's name and its inputs in round brackets. The lines below are the , and end closes it. Create the file with New ▸ Function, or type edit circle_area in the Command Window, and save it as circle_area.m:

لە .mـی خۆیدا دەژی. یەکەم دێڕ ـە: function، ، =، ناوی و لەناو کەوانەی بازنەییدا. دێڕەکانی خوارەوە ـن و end دایدەخات. بە New ▸ Function دروست بکە، یان لە ⁦Command Window⁩ بنووسە edit circle_area و بە ناوی circle_area.m هەڵیبگرە:

circle_area.mفایلی ⁦circle_area.m⁩circle_area.mMATLAB
function a = circle_area(r)
%CIRCLE_AREA  Area of a circle with radius r.
a = pi*r.^2;
end
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1

The header: output a, name circle_area, input r.

: a، ناو circle_area، r.

Lineدێڕی 2

A comment right under the header is the help text: help circle_area shows it.

ڕاستەوخۆ لە ژێر دەقی یارمەتییە: help circle_area پیشانی دەدات.

Lineدێڕی 3

The body must give the output variable a a value. .^ lets r be a whole vector.

جەستەکە دەبێت بە a بدات. .^ ڕێگە دەدات r تەواو بێت.

The header line 'function a = circle_area(r)' with labelled parts: the keyword function, the output a, the name circle_area and the input r in brackets. Below it the body 'a = pi*r.^2;' and the closing end. Above, a file tab reads circle_area.m, joined to the name by an arrow saying 'the same name'.دێڕی سەردێڕی کردار «function a = circle_area(r)» بە بەشە ناونراوەکانییەوە: وشە کلیلەییەکە function، دەرخستەکە a، ناوی circle_area و نێوخستەکە r لەناو کەوانەدا. لە ژێریدا جەستەکە «a = pi*r.^2;» و endـی داخستن. لە سەرەوە تابی فایلێک دەڵێت circle_area.m و بە تیرێک بە ناوەکەوە بەستراوە کە دەڵێت «هەمان ناو».
Anatomy of a function file: the file name and the function name must matchپێکهاتەی : ناوی و ناوی دەبێت وەک یەک بنCêIT

Now call it exactly like a built-in function — from the Command Window, a script or another function. The file must be in the current folder (the Files panel) or on MATLAB's search :

ئێستا ڕێک وەک بانگی بکە — لە ⁦Command Window⁩، لە یان لە ترەوە. دەبێت لە ئێستادا بێت (پانێڵی Files) یان لەسەر گەڕانی MATLAB:

Calling circle_areaبانگکردنی ⁦circle_area⁩MATLABType in a terminalلە تێرمیناڵدا بینووسە
a = circle_area(2)
areas = circle_area([1 2 3])
Quick checkپشکنینی خێراYou save function a = circle_area(r) … end in a file. What must the file be called?function a = circle_area(r) … end لە پاشەکەوت دەکەیت. دەبێت ناوی چی بێت؟

Creating User-Defined Functions in MATLAB: Syntax and ExamplesSpartan Professor · Englishئینگلیزی · 75K viewsبینین · 1.5K likesلایک · Partبەشی 0:00–10:44 (ofلە 17:00)

How to write a MATLAB function file: the function line with inputs and outputs, saving it under the function's name, calling it, and local variables.

نووسینی لە MATLABـدا: بە و ، بە ناوی ، بانگکردنی و .

0:00-10:44: syntax (0:30), the hypotenuse function, saving the file under the function's name (5:07), calling it and local variables (7:00). The two-output example after 10:44 belongs to a later screen.

لە ⁦0:00⁩ تا ⁦10:44⁩: ⁦(0:30)⁩، کە ژێی سێگۆشەیەکی ڕاستگۆشە (hypotenuse) دەدۆزێتەوە، بە ناوی ⁦(5:07)⁩، بانگکردنی و ⁦(7:00)⁩. نموونەی دوو دوای ⁦10:44⁩ هی بەشێکی دواتری وانەکەیە.

A function fileفایلی کردار

Names and the file-name ruleناوەکان و یاسای ناوی فایل

A function name follows the rules for variable names: it starts with a letter and uses only letters, digits and _. MATLAB connects your code with the file name, not with the name written in the header. If circle_area is saved as area.m, you must call area(2) and MATLAB's Editor warns about the mismatch — so always keep the two names the same. Avoid names MATLAB already uses (sum.m, input.m), for the same reason as with script names.

ناوی پەیڕەوی یاساکانی ناوی گۆڕاو دەکات: بە پیت دەست پێدەکات و تەنها پیت، و _ بەکار دەهێنێت. MATLAB کۆدەکەت بە ناوی ـەوە دەبەستێتەوە، نەک بەو ناوەی لە نووسراوە. ئەگەر circle_area بە ناوی area.m پاشەکەوت بکرێت، دەبێت area(2) بانگ بکەیت و Editorـی MATLAB ئاگادارت دەکاتەوە کە ناوەکان یەک ناگرنەوە — بۆیە هەمیشە هەردوو ناوەکە وەک یەک بهێڵەوە. خۆت لەو ناوانە بپارێزە کە MATLAB پێشتر بەکاری دەهێنێت (sum.m، input.m)، بە هەمان هۆکاری ناوی دەسنووسەکان.

In MATLAB you cannot type a function definition at the >> prompt; it must be saved in a file. (Octave does allow it at its prompt, but this track always saves functions in files, so the code works in both.)

لە MATLABـدا ناتوانیت پێناسەی لە دوای >> بنووسیت؛ دەبێت لە پاشەکەوت بکرێت. (Octave ڕێگە دەدات لە دوای >>ـی خۆیشی بنووسرێت، بەڵام ئەم بەشە هەمیشە لە پاشەکەوت دەکات، بۆ ئەوەی کۆدەکە لە هەردووکیاندا کار بکات.)

A function fileفایلی کردار

What happens during a callلە کاتی بانگکردندا چی ڕوو دەدات

When you type a = circle_area(2), MATLAB finds circle_area.m, creates a fresh, empty workspace for the function, copies the 2 into the input variable r, runs the body, and copies the output variable a back to your a. Then the function's workspace is thrown away.

کاتێک دەنووسیت a = circle_area(2)، MATLAB circle_area.m دەدۆزێتەوە، نوێ و بەتاڵ بۆ دروست دەکات، 2 لە rـدا کۆپی دەکات، جەستەکە جێبەجێ دەکات و a بۆ aـی خۆت دەگەڕێنێتەوە. پاشان فڕێ دەدرێت.

Animation in five frames. The value 2 leaves the Command Window and travels into a box labelled 'circle_area workspace', where it becomes r = 2. The body computes a = 12.5664. The value travels back and the Command Window shows a = 12.5664. The function's box empties: its r is gone.
Animation in five frames. The value 2 leaves the Command Window and travels into a box labelled 'circle_area workspace', where it becomes r = 2. The body computes a = 12.5664. The value travels back and the Command Window shows a = 12.5664. The function's box empties: its r is gone.
A call travels into the function's own workspace and backبانگکردنێک دەچێتە ناو تایبەتی و دەگەڕێتەوەCêIT
Quick checkپشکنینی خێراAfter a = circle_area(2) finishes, is there a variable r in your workspace?دوای تەواوبوونی a = circle_area(2)، ئایا بە ناوی r لە هەیە؟

Several inputs and several outputsچەند نێوخستە و چەند دەرخستە

Separate several inputs with commas. Several outputs go in square brackets in the header, and the caller collects them the same way:

چەند بە کۆما لێک جیا بکەرەوە. چەند لە دەچنە ناو کەوانەی چوارگۆشە و بە هەمان شێوە وەریان دەگرێتەوە:

sum_and_product.mفایلی ⁦sum_and_product.m⁩sum_and_product.mMATLAB
function [s, p] = sum_and_product(a, b)
s = a + b;
p = a*b;
end
Collecting the outputsوەرگرتنەوەی دەرخستەکانMATLABType in a terminalلە تێرمیناڵدا بینووسە
[s, p] = sum_and_product(3, 4)
x = sum_and_product(3, 4)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1

Two names in brackets receive both outputs, in order.

دوو ناو لەناو کەوانەدا هەردوو بە ڕیز وەردەگرن.

Lineدێڕی 2

With one name you get only the first output; p is computed but not returned.

بە یەک ناو تەنها یەکەم وەردەگریت؛ p هەژمار دەکرێت بەڵام ناگەڕێتەوە.

A function may also have no output — function show_bill(price, count) that only prints — and then the header has no = at all. Calling a function without saving its result puts the first output in ans, like any other expression.

دەشێت هیچ نەبێت — function show_bill(price, count) کە تەنها چاپ دەکات — ئەو کاتە هیچ =ـێکی تێدا نییە. بانگکردنی بەبێ هەڵگرتنی ئەنجامەکەی یەکەم دەخاتە ansـەوە، وەک هەر تر.

Several inputs and several outputsچەند نێوخستە و چەند دەرخستە

Optional inputs with narginنێوخستەی ئارەزوومەندانە بە nargin

Inside a function, nargin tells how many inputs the caller really gave, and nargout how many outputs were asked for (both are on the course's commands list). With nargin you can give a missing input a :

لەناو nargin دەڵێت بەڕاستی چەند داوە و nargout چەند داوا کراوە (هەردووکیان لە لیستی کۆرسەکەدان). بە nargin دەتوانیت بدەیت بە ونبوو:

cylinder_volume.mفایلی ⁦cylinder_volume.m⁩cylinder_volume.mMATLAB
function v = cylinder_volume(r, h)
if nargin < 2
    h = 1;          % default height
end
v = pi*r^2*h;
end
With and without the heightبە بەرزی و بەبێ بەرزیMATLABType in a terminalلە تێرمیناڵدا بینووسە
v = cylinder_volume(3, 10)
v = cylinder_volume(3)

Several inputs and several outputsچەند نێوخستە و چەند دەرخستە

Leaving early with returnزوو دەرچوون بە return

return ends the function at once and goes back to the caller — the function's version of break (break leaves a loop). Give the outputs their values before you return:

return یەکسەر کۆتایی پێ دەهێنێت و دەگەڕێتەوە بۆ — وەشانی breakـە بۆ (break خول جێدەهێڵێت). پێش گەڕانەوە بدە بە :

pass_or_fail.mفایلی ⁦pass_or_fail.m⁩pass_or_fail.mMATLAB
function result = pass_or_fail(mark)
if mark < 0 || mark > 100
    result = 'invalid';
    return                 % nothing below runs
end
if mark >= 50
    result = 'pass';
else
    result = 'fail';
end
end
Two callsدوو بانگکردنMATLABType in a terminalلە تێرمیناڵدا بینووسە
disp(pass_or_fail(120))
disp(pass_or_fail(64))
Quick checkپشکنینی خێرا[s, p] = sum_and_product(5, 2) — what are s and p?[s, p] = sum_and_product(5, 2) — s و p چەندن؟

A function has its own workspaceکردار شوێنی کاری تایبەتی خۆی هەیە

A script shares the Workspace with the Command Window. A function does not: every call gets its own, private workspace, and the variables made there are . MathWorks' page on function files says it plainly — variables inside a function are kept separate from the base workspace. That protects you: a function cannot accidentally change the r you were using, and it does not depend on what happens to be lying in the Workspace.

دەسنووسێک شوێنی کار لەگەڵ ⁦Command Window⁩ بەش دەکات. وا ناکات: هەر بانگکردنێک تایبەت و داخراوی خۆی وەردەگرێت و لەوێ دروست دەبن . پەڕەی MathWorks دەربارەی بە ڕوونی دەیڵێت — ناو لە سەرەکی جیا دەهێڵرێنەوە. ئەمە دەتپارێزێت: ناتوانێت بە هەڵە ئەو rـە بگۆڕێت کە بەکارت دەهێنا و پشت بەوە نابەستێت کە بە ڕێکەوت لە هەیە.

Two boxes. Left, 'base workspace' holds r = 5 and a = 12.5664. Right, 'circle_area workspace' holds its own r = 2 and a = 12.5664 during the call. An arrow carries the argument 2 from left to right into r, another carries the output a back. A crossed-out arrow shows that the function cannot see the base workspace's r = 5.دوو سندووق. لای چەپ، «شوێنی کاری سەرەکی» r = 5 و a = 12.5664 هەڵدەگرێت. لای ڕاست، «شوێنی کاری circle_area» لە کاتی بانگکردندا r = 2 و a = 12.5664ـی خۆی هەیە. تیرێک ئارگیومێنتەکە 2 لە چەپەوە بۆ ڕاست دەباتە ناو r، تیرێکی تر دەرخستەکە a دەگەڕێنێتەوە. تیرێکی خەتلێدراو پیشان دەدات کە کردارەکە ناتوانێت r = 5ـی شوێنی کاری سەرەکی ببینێت.
Two separate workspaces: only arguments go in, only outputs come outدوو جیا: تەنها دەچنە ژوورەوە، تەنها دێنە دەرەوەCêIT
The function's r does not touch yoursrـی کردارەکە دەست لە rـی تۆ ناداتMATLABType in a terminalلە تێرمیناڵدا بینووسە
r = 5;
a = circle_area(2);
r
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 3

Inside the call, r was 2 — but that was the function's own r.

لەناو بانگکردنەکەدا r 2 بوو — بەڵام ئەوە rـی تایبەتی بوو.

The other side: a function cannot see your Workspace either. If the body uses a name that is neither an input nor made inside the function, MATLAB stops with Unrecognized function or variable — even if a variable with that name exists in the Command Window. Pass everything the function needs as an argument.

لایەنەکەی تر: تۆش نابینێت. ئەگەر جەستەکە ناوێک بەکار بهێنێت کە نە و نە لەناو دروست کراوە، MATLAB بە ⁦Unrecognized function or variable⁩ دەوەستێت — تەنانەت ئەگەر بەو ناوە لە ⁦Command Window⁩ـدا هەبێت. هەموو ئەو شتانەی پێویستی پێیانە وەک بنێرە.

Script or function? یان ؟
FeatureتایبەتمەندیScriptFunction file
First word of the fileیەکەم وشەی anythingهەر شتێکfunction
Inputs and outputs و none; it uses the Workspaceنییە؛ بەکار دەهێنێتarguments in, outputs back دەچنە ژوورەوە، دەگەڕێنەوە
Variablesshared with the Command Window, they stayلەگەڵ ⁦Command Window⁩ بەش دەکرێن و دەمێننەوەprivate; gone after the callتایبەتن؛ دوای بانگکردن نامێنن
How you run itچۆن جێبەجێی دەکەیتtype its name or press Runناوەکەی بنووسە یان Run دابگرەcall it with arguments: circle_area(2)بە بانگی بکە: circle_area(2)
Good forباشە بۆa quick experiment, a lab taskتاقیکردنەوەیەکی خێرا، ئەرکێکی تاقیگەa tool you reuse and testئامرازێک کە دووبارە بەکاری دەهێنیتەوە و تاقیی دەکەیتەوە
Quick checkپشکنینی خێراYour Workspace has rate = 0.05. A function file uses rate in its body but has no input called rate. What happens when you call it? rate = 0.05ـی تێدایە. لە جەستەکەیدا rate بەکار دەهێنێت بەڵام هیچ بە ناوی rate نییە. کاتێک بانگی دەکەیت چی ڕوو دەدات؟

Where functions may liveکردارەکان لە کوێ دەتوانن بژین

This track's rule is simple: one function per .m file, with the same name. That works everywhere, in MATLAB and in Octave. You will still meet two other places in other people's code:

یاسای ئەم بەشە سادەیە: یەک بۆ هەر .m، بە هەمان ناو. ئەمە لە هەموو شوێنێک کار دەکات، لە MATLAB و Octaveـیشدا. لەگەڵ ئەوەشدا لە کۆدی کەسانی تردا دوو شوێنی تر دەبینیت:

  • in a function file. After the main function, the same file may hold helper functions that only that file can call.
  • Local functions in a script. MATLAB lets a script end with function definitions; before release R2024a they had to come after the last line of script code.
  • لە . دوای ، هەمان دەتوانێت هەڵبگرێت کە تەنها ئەو دەتوانێت بانگیان بکات.
  • لە . MATLAB ڕێگە دەدات بە پێناسەی کۆتایی بێت؛ پێش وەشانی ⁦R2024a⁩ دەبوو دوای دوایین دێڕی کۆدی بێن.
A local function at the end of a scriptکردارێکی ناوخۆیی لە کۆتایی دەسنووسێکداshop_bill.mMATLABType in a terminalلە تێرمیناڵدا بینووسە
% shop_bill.m - a script with a local function (MATLAB)
prices = [1500 2750 900];
fprintf('Total: %d IQD\n', add_tax(sum(prices)))

function t = add_tax(x)
t = round(1.05*x);
end
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 5-7

Only shop_bill.m can call add_tax.

تەنها shop_bill.m دەتوانێت add_tax بانگ بکات.

Octave treats such files differently. It decides by the first word: a file that starts with function is a function file. A script that defines functions must therefore start with something else — its manual uses a harmless 1; as the first line — and Octave defines a script's functions as it reaches them, so they must stand before the lines that call them. The MATLAB layout above (functions at the end) fails in Octave. One function per file avoids all of this.

Octave بە شێوەیەکی تر مامەڵە لەگەڵ ئەم جۆرە دەکات. بە یەکەم وشە بڕیار دەدات: کە بە function دەست پێبکات . بۆیە کە پێناسە دەکات دەبێت بە شتێکی تر دەست پێبکات — ڕێبەرەکەی 1;ـێکی بێزیان وەک یەکەم دێڕ بەکار دەهێنێت — و Octave کاتێک دەگاتە سەریان پێناسە دەکات، بۆیە دەبێت پێش ئەو دێڕانە بن کە بانگیان دەکەن. ڕێکخستنەکەی سەرەوەی MATLAB ( لە کۆتاییدا) لە Octaveـدا سەرناکەوێت. یەک بۆ هەر هەموو ئەمانە لادەبات.

Quick checkپشکنینی خێراYou want add_tax to run in MATLAB and Octave without surprises. What should you do?دەتەوێت add_tax لە MATLAB و Octaveـدا بێ سەرسوڕمان کار بکات. چی بکەیت؟

Anonymous functions: a function in one lineکردارە بێناوەکان: کردارێک لە یەک دێڕدا

For a short formula a whole file is too much. An is written straight into a variable: @, the inputs in brackets, then one expression. The guide's example function is this cubic:

بۆ فۆرموولەیەکی کورت تەواو زۆرە. ڕاستەوخۆ لەناو دەنووسرێت: @، لەناو کەوانەدا، پاشان یەک . نموونەی ڕێبەرەکە ئەم سێپلەییەیە:

Two anonymous functionsدوو کرداری بێناوMATLABType in a terminalلە تێرمیناڵدا بینووسە
f = @(x) x.^3 - 3*x - 1;
f(2)
f([-2 0 2])
fare = @(km, rate) 3000 + rate*km;
fare(5, 750)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1

f now holds a — a value that stands for a function. Its type is function_handle.

ئێستا f هەڵدەگرێت — کە نوێنەرایەتیی دەکات. جۆرەکەی function_handleـە.

Lineدێڕی 3

.^ makes f work on a whole vector at once.

.^ وا دەکات f لەسەر تەواو بە یەکجار کار بکات.

Lineدێڕی 4-5

Several inputs are separated by commas: a taxi fare of 3000 IQD plus 750 per km.

چەند بە کۆما جیا دەکرێنەوە: کرێی تاکسی ⁦3000⁩ دینار و ⁦750⁩ بۆ هەر کیلۆمەترێک.

Rules to remember: only one expression (no if, no loop inside), one output, and no file. @sin makes a handle to an existing function — h = @sin; h(pi/2) gives 1. Anonymous functions are written the same way in Octave.

ئەم یاسایانە لە بیرت بێت: تەنها یەک (نە if، نە لە ناویدا)، یەک و پێویستی بە نییە. @sin بۆ ئامادە دروست دەکات — h = @sin; h(pi/2) 1 دەدات. لە Octaveـیشدا بە هەمان شێوە دەنووسرێن.

MATLAB Crash Course for BeginnersfreeCodeCamp.org · Englishئینگلیزی · 1.7M viewsبینین · 37K likesلایک · Partبەشی 45:09–47:57 (ofلە 1:57:45)

A MATLAB beginner course by Phil Parisi: the Command Window, variables, vectors and matrices, indexing, scripts, sections and naming rules, each in short parts.

کۆرسێکی سەرەتایی MATLAB لەلایەن ⁦Phil Parisi: Command Window⁩، ، و ، ، ، بەشەکان و یاساکانی ناونان، هەر یەکەیان بە بەشێکی کورت.

Chapter 'Anonymous Functions' (45:09-47:57): y = @(x) (-(x-3).^2)+10 turns a formula into a handle, called as y(20.2).

بەشی Anonymous Functions (لە ⁦45:09⁩ تا ⁦47:57⁩): y = @(x) (-(x-3).^2)+10 دەکاتە کە وەک y(20.2) بانگ دەکرێت.

Anonymous functions: a function in one lineکردارە بێناوەکان: کردارێک لە یەک دێڕدا

Values are captured when the handle is madeنرخەکان لە کاتی دروستکردنی ئاماژەی کردارەکەدا دەگیرێن

An anonymous function may use variables that are not inputs. It takes a copy of their values at the moment it is created; changing the variable later does not change the handle:

دەتوانێت بەکار بهێنێت کە نین. کۆپییەکی لە ساتی دروستبوونیدا وەردەگرێت؛ گۆڕینی دواتر ناگۆڕێت:

A captured valueنرخێکی گیراوMATLABType in a terminalلە تێرمیناڵدا بینووسە
rate = 750;
fare = @(km) 3000 + rate*km;
rate = 1000;      % change rate afterwards...
fare(5)           % ...the handle still uses 750
Quick checkپشکنینی خێراk = 2; g = @(x) k*x; k = 10; g(3) — what is the answer?k = 2; g = @(x) k*x; k = 10; g(3) — وەڵامەکە چەندە؟

Functions that take functionsکردارەکان کە کردار وەردەگرن

A function handle is a value, so you can pass it to another function. Several MATLAB tools work this way — you give them the function itself, and they decide where to evaluate it:

، بۆیە دەتوانیت بیدەیت بە تر. چەند ئامرازێکی MATLAB بەم شێوەیە کار دەکەن — خودی یان دەدەیتێ و خۆیان بڕیار دەدەن لە کوێ هەژماری بکەن:

Passing handles to fplot, fzero, integral and fevalناردنی ئاماژەکانی کردار بۆ fplot، fzero، integral و fevalMATLABType in a terminalلە تێرمیناڵدا بینووسە
f = @(x) x.^3 - 3*x - 1;
fplot(f, [-2 2])                      % draws the curve
r = fzero(f, [1 2])                   % a root between 1 and 2
q = integral(@(x) exp(-x.^2), 0, 1)   % area under a curve
feval(f, 2)                           % the same as f(2)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2

fplot evaluates f at many points and draws it — see plotting a function handle.

fplot f لە زۆر خاڵدا هەژمار دەکات و دەیکێشێت — بڕوانە کێشانی ئاماژەیەکی کردار.

Lineدێڕی 3

fzero searches the interval for a point where f changes sign — the whole method is the root-finding project.

fzero لە بەدوای خاڵێکدا دەگەڕێت کە هێمای f تێیدا دەگۆڕێت — هەموو ڕێگاکە پڕۆژەی دۆزینەوەی ڕەگە.

Lineدێڕی 4

integral needs a handle written with .*, ./, .^, because it evaluates many x values at once. There is no formula for this area; MATLAB finds 0.7468.

integral پێویستی بە هەیە کە بە .*، ./، .^ نووسرابێت، چونکە زۆر x بە یەکجار هەژمار دەکات. فۆرموولە بۆ ئەم ڕووبەرە نییە؛ ⁦MATLAB 0.7468⁩ دەدۆزێتەوە.

Lineدێڕی 5

feval is listed in the commands list. With a handle you can simply write f(2).

feval لە لیستی . بە دەتوانیت بە سادەیی بنووسیت f(2).

integral is the current name for numerical integration in MATLAB and Octave; the old quad and quadl are no longer recommended in MATLAB (more in the numerical methods project). The area idea itself belongs to calculus: the .

integral ناوی ئێستای ژمارەییە لە MATLAB و Octaveـدا؛ quad و quadlـی کۆن چیتر لە MATLABـدا پێشنیار ناکرێن (زیاتر لە پڕۆژەی ڕێگە ژمارەییەکان). بیرۆکەی ڕووبەرەکە خۆی هی ژمێرکارییە: .

Quick checkپشکنینی خێراWhy must the handle passed to integral use .^ and not ^?بۆچی کە دەدرێت بە integral دەبێت .^ بەکار بهێنێت نەک ^؟

Timing your code: tic and tocکاتپێوانی کۆدەکەت: tic و toc

The commands list names three timing tools: tic/toc, cputime and clock. tic starts a stopwatch and toc prints the time since tic. Here a loop and a one-line vector sum compute the same total, ∑k=11061/k2\sum_{k=1}^{10^6} 1/k^2:

لیستی سێ ئامرازی کاتپێوان ناو دەبات: tic/toc، cputime و clock. tic وەک کاتپێوی پێشبڕکێ دەست بە پێوانی کات دەکات و toc ئەو کاتە چاپ دەکات کە لە ticـەوە تێپەڕیوە. لێرەدا و کۆکردنەوەیەکی یەک دێڕیی هەمان کۆ هەژمار دەکەن، ∑k=11061/k2\sum_{k=1}^{10^6} 1/k^2:

A loop against a vector sumخولێک بەرامبەر کۆی ئاڕاستەبڕMATLABType in a terminalلە تێرمیناڵدا بینووسە
tic
total = 0;
for k = 1:1000000
    total = total + 1/k^2;
end
toc
fprintf('loop:   %.6f\n', total)
tic
total2 = sum(1./(1:1000000).^2);
toc
fprintf('vector: %.6f\n', total2)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 9

1./(1:1000000).^2 builds all one million terms at once with element-wise operators (element-wise operations).

1./(1:1000000).^2 هەموو یەک ملیۆن بڕگە بە یەکجار بە دروست دەکات (کارەکانی توخم بە توخم).

Both give 1.644933 (close to π2/6≈1.644934\pi^2/6 \approx 1.644934). Modern MATLAB runs simple loops quickly, so the difference may be smaller than you expect; time short code several times, or use timeit. About the other two: cputime measures the processor time MATLAB has used, and its own page recommends tic/toc or timeit for measuring performance; clock returns the date and time as six numbers and is no longer recommended — new code uses datetime.

هەردووکیان ⁦1.644933⁩ دەدەن (نزیک لە π2/6≈1.644934\pi^2/6 \approx 1.644934). MATLABـی نوێ سادە بە خێرایی جێبەجێ دەکات، بۆیە لەوانەیە جیاوازییەکە لەوەی چاوەڕێی دەکەیت بچووکتر بێت؛ کۆدی کورت چەند جار کاتپێوان بکە، یان timeit بەکار بهێنە. دەربارەی دووانەکەی تر: cputime ئەو کاتەی پرۆسێسەر دەپێوێت کە MATLAB بەکاری هێناوە و پەڕەی خۆی بۆ پێوانی کارایی tic/toc یان timeit پێشنیار دەکات؛ clock بەروار و کات وەک شەش ژمارە دەگەڕێنێتەوە و چیتر پێشنیار ناکرێت — کۆدی نوێ datetime بەکار دەهێنێت.

Quick checkپشکنینی خێراWhat does toc measure?toc چی دەپێوێت؟

MATLAB Crash Course for BeginnersfreeCodeCamp.org · Englishئینگلیزی · 1.7M viewsبینین · 37K likesلایک · Partبەشی 1:40:09–1:42:57 (ofلە 1:57:45)

A MATLAB beginner course by Phil Parisi: the Command Window, variables, vectors and matrices, indexing, scripts, sections and naming rules, each in short parts.

کۆرسێکی سەرەتایی MATLAB لەلایەن ⁦Phil Parisi: Command Window⁩، ، و ، ، ، بەشەکان و یاساکانی ناونان، هەر یەکەیان بە بەشێکی کورت.

Chapter 'Calculation Time' (1:40:09-1:42:57): tic and toc time sum(A == 3) against a for loop on ten million numbers.

بەشی Calculation Time (لە ⁦1:40:09⁩ تا ⁦1:42:57⁩): tic و toc کاتی sum(A == 3) و کاتی لەسەر دە ملیۆن ژمارە دەپێون و بەراوردیان دەکەن.

Common mistakesهەڵە باوەکان

Function mistakes and their fixesهەڵەکانی و چاککردنیان
MistakeهەڵەWhat happensچی ڕوو دەداتFixچاککردن
File name ≠ function name (circle_area saved as area.m)ناوی ≠ ناوی (circle_area بە ناوی area.m)circle_area(2) is unknown; MATLAB knows the function as areacircle_area(2) نەناسراوە؛ MATLAB بە ناوی area دەناسێتgive the file the function's nameناوی بدە بە
The file is not in the current folder لە ئێستادا نییەUnrecognized function or variable: ⁦Unrecognized function or variable⁩change folder (Files panel or cd) or add the folder to the path بگۆڕە (پانێڵی Files یان cd) یان زیاد بکە بۆ
Calling a script with arguments: myscript(3)بانگکردنی بە : myscript(3)an error: a script takes no inputs: هیچ وەرناگرێتturn it into a function file with a headerبیکە بە بە
@(x) x^3 given a vector@(x) x^3 و a matrix-power error, or a warning from fplot توانی ، یان ئاگادارییەک لە fplotـەوەwrite x.^3, .*, ./x.^3، .*، ./ بنووسە
Forgetting to give the output a valueلەبیرچوونی دانانی بۆ an error saying the output was not assigned کە دەڵێت پێ نەدراوەset every output on every path, also before returnلە هەموو ڕێگایەکدا بدە بە هەموو ، پێش returnـیش
Expecting the function to see Workspace variablesچاوەڕوانیی ئەوەی ببینێتUnrecognized function or variable: ⁦Unrecognized function or variable⁩pass them as argumentsوەک بیاننێرە
Collecting one output from a two-output functionوەرگرتنی یەک لە کە دوو هەیەyou silently get only the firstبە بێدەنگی تەنها یەکەمیان وەردەگریت[s, p] = …[s, p] = …
Writing eval with textنووسینی eval لەگەڵ دەقslow, unclear, unsafeهێواش، ناڕوون، ناسەلامەتuse a handle or feval یان feval بەکار بهێنە
Quick checkپشکنینی خێراfunction y = twice(x) is saved in double_it.m. Which call works?function y = twice(x) لە double_it.mـدا پاشەکەوت کراوە. کام بانگکردن کار دەکات؟

Practiceڕاهێنان

Exerciseڕاهێنان1. The hypotenuse1. ژێی سێگۆشە

Write hypotenuse.m: c = hypotenuse(a, b) returns a2+b2\sqrt{a^2+b^2} and works on vectors too. Test hypotenuse(3, 4) and hypotenuse([3 5], [4 12]).

hypotenuse.m بنووسە: c = hypotenuse(a, b) a2+b2\sqrt{a^2+b^2} دەگەڕێنێتەوە و لەسەر کار دەکات. hypotenuse(3, 4) و hypotenuse([3 5], [4 12]) تاقی بکەرەوە.

Show answerوەڵامەکە پیشان بدە
hypotenuse.mMATLAB
function c = hypotenuse(a, b)
c = sqrt(a.^2 + b.^2);
end
MATLABType in a terminalلە تێرمیناڵدا بینووسە
hypotenuse(3, 4)
hypotenuse([3 5], [4 12])
Exerciseڕاهێنان2. A clamp function (piecewise)2. کردارێکی clamp (پارچەپارچە)

A clamp keeps a value inside [lo, hi]: below lo it gives lo, above hi it gives hi, otherwise the value itself — a piecewise function. Write y = clamp(x, lo, hi) so it also works on vectors. Test with clamp([-3 4.5 12], 0, 10).

clamp لەناو ⁦[lo, hi]⁩ـدا دەهێڵێتەوە: لە خوار lo دەبێتە lo، لە سەرووی hi دەبێتە hi، ئەگینا خودی — نەخشەیەکی پارچەپارچە. y = clamp(x, lo, hi) بنووسە بە شێوەیەک کە لەسەر کار بکات. بە clamp([-3 4.5 12], 0, 10) تاقیی بکەرەوە.

Hintئاماژە

max and min with two arguments compare element by element.

max و min بە دوو بە بەراورد دەکەن.

Show answerوەڵامەکە پیشان بدە
clamp.mMATLAB
function y = clamp(x, lo, hi)
y = min(max(x, lo), hi);
end
MATLABType in a terminalلە تێرمیناڵدا بینووسە
clamp([-3 4.5 12], 0, 10)

max(x, lo) lifts everything below lo; min(…, hi) cuts everything above hi — element by element, so no if is needed.

max(x, lo) هەموو ئەوەی لە خوار loـیە بەرز دەکاتەوە؛ min(…, hi) هەموو ئەوەی لە سەرووی hiـیە دەبڕێت — بە ، بۆیە پێویست بە if ناکات.

Exerciseڕاهێنان3. The quadratic solver as a function3. چارەسەرکەری هاوکێشەی پلەدوو وەک کردار

Turn the corrected quadratic solver into [x1, x2] = quad_roots(a, b, c) for a≠0a \ne 0. Test (a,b,c)=(1,−3,2)(a, b, c) = (1, -3, 2), (2,−7,3)(2, -7, 3) and (1,2,5)(1, 2, 5).

چارەسەرکەری چاککراوی هاوکێشەی پلەدوو بکە بە [x1, x2] = quad_roots(a, b, c) بۆ a≠0a \ne 0. (a,b,c)=(1,−3,2)(a, b, c) = (1, -3, 2)، (2,−7,3)(2, -7, 3) و (1,2,5)(1, 2, 5) تاقی بکەرەوە.

Show answerوەڵامەکە پیشان بدە
quad_roots.mMATLAB
function [x1, x2] = quad_roots(a, b, c)
d = b^2 - 4*a*c;           % sqrt of a negative d gives complex roots
x1 = (-b + sqrt(d))/(2*a);
x2 = (-b - sqrt(d))/(2*a);
end
MATLABType in a terminalلە تێرمیناڵدا بینووسە
[x1, x2] = quad_roots(1, -3, 2)
[x1, x2] = quad_roots(2, -7, 3)
[x1, x2] = quad_roots(1, 2, 5)
Exerciseڕاهێنان4. An anonymous converter4. گۆڕەرێکی بێناو

Make an anonymous function c2f that turns °C into °F (F=95C+32F = \tfrac{9}{5}C + 32) and apply it to the vector [0 25 40] in one call.

بە ناوی c2f دروست بکە کە °C دەکات بە °F (F=95C+32F = \tfrac{9}{5}C + 32) و لە یەک بانگکردندا لەسەر [0 25 40] جێبەجێی بکە.

Show answerوەڵامەکە پیشان بدە
MATLABType in a terminalلە تێرمیناڵدا بینووسە
c2f = @(c) 9/5*c + 32;
c2f([0 25 40])
Exerciseڕاهێنان5. Three outputs5. سێ دەرخستە

Write [m, hi, lo] = mark_stats(marks) that returns the mean, the highest and the lowest mark. Test with Shilan's marks [72 88 95 60].

[m, hi, lo] = mark_stats(marks) بنووسە کە ، بەرزترین و نزمترین نمرە بگەڕێنێتەوە. بە نمرەکانی شیلان [72 88 95 60] تاقیی بکەرەوە.

Show answerوەڵامەکە پیشان بدە
mark_stats.mMATLAB
function [m, hi, lo] = mark_stats(marks)
m = mean(marks);
hi = max(marks);
lo = min(marks);
end
MATLABType in a terminalلە تێرمیناڵدا بینووسە
[m, hi, lo] = mark_stats([72 88 95 60])
Exerciseڕاهێنان6. Predict the output6. دەرخستەکە پێشبینی بکە

What does this print, and why? a = 3; f = @(x) a + x; a = 100; disp(f(1))

ئەمە چی چاپ دەکات و بۆچی؟ a = 3; f = @(x) a + x; a = 100; disp(f(1))

Show answerوەڵامەکە پیشان بدە

It prints 4. The handle captured a = 3 when it was created; the later a = 100 does not reach it.

4 چاپ دەکات. کاتێک دروست کرا ⁦a = 3⁩ـی گرت؛ a = 100ـی دواتر ناگاتە ناوی.

Summaryپوختە

  • A function file starts with function [outputs] = name(inputs), ends with end, and is saved as name.m in the current folder or on the path.
  • Call it like a built-in; several outputs come back with [a, b] = …, in header order. nargin gives defaults; return leaves early.
  • A function has its own workspace: only arguments go in and only outputs come out. Scripts share the Workspace. Avoid global.
  • One function per file runs in MATLAB and Octave; local functions in scripts are MATLAB's layout (Octave needs them first, after 1;).
  • f = @(x) x.^3 - 3*x - 1 is an anonymous function; f is a function handle that captures values when made and can be passed to fplot, fzero, integral, feval. Never eval.
  • tic … toc times code; cputime and clock are older tools (timeit, datetime today).
  • بە function [outputs] = name(inputs) دەست پێدەکات، بە end کۆتایی دێت و بە ناوی name.m لە ئێستا یان لەسەر پاشەکەوت دەکرێت.
  • وەک بانگی بکە؛ چەند بە [a, b] = … و بە ڕیزبەندیی دەگەڕێنەوە. nargin دەدات؛ return زوو دەردەچێت.
  • تایبەتی خۆی هەیە: تەنها دەچنە ژوورەوە و تەنها دێنە دەرەوە. بەش دەکەن. خۆت لە global بپارێزە.
  • یەک بۆ هەر لە MATLAB و Octaveـدا کار دەکات؛ لە ڕێکخستنی MATLABـن (Octave پێویستی پێیانە لە سەرەتادا بن، دوای 1;).
  • f = @(x) x.^3 - 3*x - 1 ؛ f کە لە کاتی دروستبووندا دەگرێت و دەتوانرێت بدرێت بە fplot، fzero، integral، feval. هەرگیز eval نا.
  • tic … toc کاتی کۆد دەپێوێت؛ cputime و clock ئامرازی کۆنترن (ئەمڕۆ timeit، datetime).

If you know Python: def name(inputs): … return value there, the output names in the header here; Python returns several values as a tuple, MATLAB as named outputs — see the anatomy of a function and several return values.

ئەگەر Python دەزانیت: لەوێ def name(inputs): … return value، لێرە ناوی لە ؛ Python چەند وەک tuple دەگەڕێنێتەوە، MATLAB وەک — بڕوانە پێکهاتەی کردارێک و چەند نرخی گەڕاوە.

Review questionsپرسیارەکانی پێداچوونەوە
What is the difference between a script and a function file?جیاوازیی نێوان دەسنووس و فایلی کردار چییە؟

A function file starts with function, takes arguments, returns outputs and has its own workspace; a script has no inputs or outputs and shares the Workspace.

بە function دەست پێدەکات، وەردەگرێت، دەگەڕێنێتەوە و خۆی هەیە؛ نە و نە هەیە و بەش دەکات.

When is an anonymous function enough?کەی کردارێکی بێناو بەسە؟

When the job is one expression with one output, such as a formula to plot or to pass to fzero.

کاتێک کارەکە یەک بە یەک ، وەک فۆرموولەیەک بۆ کێشان یان ناردن بۆ fzero.

Why does circle_area use .^?بۆچی circle_area .^ بەکار دەهێنێت؟

So that circle_area([1 2 3]) squares each radius; ^ would try a matrix power and fail on a vector.

بۆ ئەوەی circle_area([1 2 3]) هەر نیوەتیرەیەک دووجا بکات؛ ^ هەوڵی توانی دەدات و لەسەر سەرناکەوێت.

Lesson complete!وانەکە تەواو بوو!

Well done. Review the key terms, then go on to the next lesson.دەستخۆش. سەیرێکی زاراوە سەرەکییەکان بکەرەوە، پاشان بڕۆ بۆ وانەی داهاتوو.

Key termsزاراوە سەرەکییەکان

Next lessonوانەی داهاتوو

Plotting Graphsکێشانی هێڵکارییەکان

References and further readingسەرچاوەکان و خوێندنەوەی زیاتر

This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.