MATLABMATLAB · Chapterبەش 5 · Lectureوانە 5.4
for Loops: Sums, Series and Searchingخولەکانی for: کۆکردنەوە، زنجیرە و گەڕان
Repeat a block for every value of a vector with for … end, understand the loop variable, add series with an accumulator () and an alternating sign (J = -J), trace the lab's loops to find the factorial(n) slip, search for the largest and smallest input, put if and switch inside a loop, and fill a table with nested loops after preallocating it with zeros.
بە for … end بلۆکێک بۆ هەر دووبارە بکەرەوە، لە تێبگە، زنجیرە بە () و نیشانەی ئاڵوگۆڕ (J = -J) کۆ بکەرەوە، تاقیگە بەدوادا بچۆ بۆ دۆزینەوەی هەڵەی factorial(n)، بەدوای گەورەترین و بچووکترین بگەڕێ، if و switch بخەرە ناو و دوای بە zeros، خشتەیەک بە پڕ بکەرەوە.
What you will learnچی فێر دەبیت
- Write for loops over ranges, countdowns and lists, and predict the value of the loop variable in each turn.
- Add up series with an accumulator, including an alternating sign, and write the same sum in one vectorised line.
- Trace a loop with a trace table and find mistakes such as factorial(n) instead of factorial(i).
- Find the largest and smallest of several inputs, starting from the first value.
- Put if and switch inside loops, and fill a preallocated matrix with nested loops.
- بەسەر زنجیرە، ژماردنی بەرەو خوار و لیستدا بنووسیت و لە هەر پێشبینی بکەیت.
- بە زنجیرە کۆ بکەیتەوە (لەوانە بە نیشانەی ئاڵوگۆڕ) و هەمان کۆ لە یەک دێڕدا بێ بنووسیت.
- بە بەدوادا بچیت و هەڵەی وەک factorial(n) لە جیاتی factorial(i) بدۆزیتەوە.
- گەورەترین و بچووکترینی چەند بدۆزیتەوە، بە دەستپێکردن لە یەکەم .
- if و switch بخەیتە ناو و پێشتر ئامادەکراو بە پڕ بکەیتەوە.
Repeating a block: forدووبارەکردنەوەی بلۆکێک: for
Repetition is the third building block of every algorithm. A repeats a block of commands once for each value of a vector: for k = 1:5 … end runs its body five times, with k equal to 1, then 2, then 3, 4 and 5. k is the ; each repetition is one (one turn). Like if, every for ends with end.
دووبارەکردنەوە سێیەم بەردی بناغەی هەموو . بلۆکێک لە بۆ هەر جارێک دووبارە دەکاتەوە: for k = 1:5 … end ناوەڕۆکەکەی پێنج جار جێبەجێ دەکات، k یەکەم جار 1ـە، پاشان 2، پاشان 3، 4 و 5. k ؛ هەر دووبارەبوونەوەیەک (یەک جار). وەک if، هەموو forـێک بە end کۆتایی دێت.
for k = 1:5
fprintf('%d x 7 = %d\n', k, 7*k)
end1 x 7 = 7 2 x 7 = 14 3 x 7 = 21 4 x 7 = 28 5 x 7 = 35
The flowchart (redrawn from the course's Kurdish guide) shows a detail: if the vector is empty — for example 1:0 — the body never runs. If you know Python: there you write for k in range(1, 6) and the end is left out (range); in MATLAB 1:5 includes 5. All code here also runs in GNU Octave and the free version of MATLAB Online (free ways to practise).
(کە لە ڕێبەرە کوردییەکەی وانەکەوە دووبارە کێشراوەتەوە) وردەکارییەک پیشان دەدات: ئەگەر بەتاڵ بێت — بۆ نموونە 1:0 — ناوەڕۆکەکە هەرگیز جێبەجێ نابێت. ئەگەر Python دەزانیت: لەوێ for k in range(1, 6) دەنووسیت و کۆتاییەکە دەردەکرێت (range)؛ لە MATLABـدا 1:5 5ـیش دەگرێتەوە. هەموو کۆدی ئێرە لە GNU Octave و وەشانی بێبەرانبەری MATLAB Onlineـیشدا کار دەکات (ڕێگە بێبەرانبەرەکانی ڕاهێنان).
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 'For Loops' (1:28:20-1:40:09): for i = 1:10 ... end, then a loop with an if inside that counts the 3s in a vector.
بەشی For Loops (لە 1:28:20 تا 1:40:09): for i = 1:10 ... end، پاشان کە ifـێکی تێدایە و ژمارەی 3ـەکانی ناو دەژمێرێت.
Repeating a block: forدووبارەکردنەوەی بلۆکێک: for
Any vector can drive a loopهەر ئاڕاستەبڕێک دەتوانێت خولێک بەڕێوە ببات
The values after = can be any row vector: a range with a step (colon ranges), a range that counts down, or a list of numbers with uneven gaps. MathWorks' own example loops over [1 5 8 17].
ئەو دوای = دەتوانن هەر ڕیزی بن: زنجیرەیەک بە هەنگاو (زنجیرەکانی دوو خاڵ)، زنجیرەیەک کە بەرەو خوار دەژمێرێت، یان لیستێک ژمارە کە دووریی نێوانیان یەکسان نییە. نموونەکەی خودی MathWorks بەسەر [1 5 8 17]ـدا دەخولێتەوە.
for k = 10:-2:0
fprintf('%d ', k)
end
fprintf('\n')
for x = [3 7 1]
fprintf('%d squared is %d\n', x, x^2)
end10 8 6 4 2 0 3 squared is 9 7 squared is 49 1 squared is 1
One surprise: MATLAB takes the vector column by column. A row vector has one value per column, so all is well. A column vector such as [3; 7; 1] is a single column, so the loop runs once, with x equal to the whole column. MathWorks' advice: to loop over a column vector, transpose it first, for x = v'.
سەرسوڕهێنەرییەک: MATLAB ستوون بە ستوون وەردەگرێت. ڕیزی بۆ هەر ستوونێک یەک هەیە، بۆیە هەموو شتێک باشە. ستوونی وەک [3; 7; 1] تەنها یەک ستوونە، بۆیە یەک جار جێبەجێ دەبێت و x یەکسانە بە هەموو ستوونەکە. ئامۆژگاریی MathWorks: بۆ خولانەوە بەسەر ستوونیدا، سەرەتا بیگۆڕە بۆ ڕیز: for x = v'.
for x = [3; 7; 1]
x
endx =
3
7
1Repeating a block: forدووبارەکردنەوەی بلۆکێک: for
The loop variable belongs to the loopگۆڕاوی خول هی خولەکەیە
At the start of each turn MATLAB gives the loop variable the next value of the vector, whatever happened before. Two consequences: a value the variable had before the loop is simply overwritten (the course guide shows the same idea with i := 20 before a loop), and changing the variable inside the body does not change the next turn — MathWorks says the for statement overrides such changes. After the loop the variable keeps its last value.
لە سەرەتای هەر MATLAB دواتری دەدات بە ، هەرچی پێشتر ڕوویدابێت. دوو دەرەنجام: ئەو پێش هەیبوو تەنها دەسڕدرێتەوە (ڕێبەرەکەی وانەکە هەمان بیرۆکە بە i := 20 پێش پیشان دەدات). هەروەها گۆڕینی لەناو ناوەڕۆکەکەدا دواتر ناگۆڕێت — MathWorks دەڵێت ڕستەی for ئەو گۆڕانکارییانە پشتگوێ دەخات. دوای ، دوایین دەهێڵێتەوە.
k = 20;
for k = 1:3
a = k;
b = k^2;
fprintf('%d, %d\n', a, b)
end
k1, 1
2, 4
3, 9
k =
3for k = 1:3
k = k*10;
disp(k)
end 10
20
30Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
This changes
konly for the rest of this turn; the next turn still starts with 2, then 3.ئەمە تەنها بۆ باقیی ئەم
kدەگۆڕێت؛ دواتر هەر بە 2 دەست پێدەکات، پاشان 3.
Adding up in a loop: the accumulatorکۆکردنەوە لەناو خولێکدا: گۆڕاوی کۆکردنەوە
To add many terms, keep a running total in a variable — an . Set it to 0 before the loop, add one term in each turn, and read it after the loop. A loop that adds terms is exactly a sum written with (a loop is a sigma). A lab program adds the terms :
بۆ کۆکردنەوەی زۆر بڕ، کۆیەکی بەردەوام لە هەڵبگرە — . پێش بیکە بە 0، لە هەر یەک بڕ زیاد بکە و دوای بیخوێنەوە. کە بڕەکان کۆ دەکاتەوە ڕێک ئەو کۆیەیە کە بە دەنووسرێت (خولێک سیگمایەکە). تاقیگە بڕەکانی کۆ دەکاتەوە:
total = 0;
n = input('Enter the last number: ');
for i = 1:n
total = total + i/factorial(i);
end
totalEnter the last number: 5
total =
2.7083Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
Start at 0 — before the loop, never inside it.
بە 0 دەست پێبکە — پێش ، هەرگیز لەناویدا نا.
- Lineدێڕی 4
New total = old total + this turn's term.
factorial(i)uses the loop variable.کۆی نوێ = کۆی کۆن + بڕی ئەم .
factorial(i)بەکار دەهێنێت.
Watch the total grow. Since , the sum is , which approaches the number e, : six terms already give 2.7167.
سەیری گەشەکردنی کۆکە بکە. لەبەر ئەوەی ، کۆکە دەبێتە کە لە ژمارەی e () نزیک دەبێتەوە: شەش بڕ پێشتر 2.7167 دەدەن.


A for loop adds up a series: a running total is updated in every turn, shown first as a flowchart, then as a MATLAB script.
کۆی چەند ژمارەیەک دەدۆزێتەوە: لە هەر نوێ دەکرێتەوە؛ سەرەتا وەک ، پاشان وەک MATLAB.
Problem (0:00), loop structure (2:03), flowchart (3:15), MATLAB script (6:24).
کێشەکە (0:00)، پێکهاتەی (2:03)، (3:15) و MATLAB (6:24).
Adding up in a loop: the accumulatorکۆکردنەوە لەناو خولێکدا: گۆڕاوی کۆکردنەوە
Spot the mistake: factorial(n)هەڵەکە بدۆزەرەوە: factorial(n)
A second lab program should add . It contains one small slip — find it before reading on:
دووەمی تاقیگە دەبێت کۆ بکاتەوە. هەڵەیەکی بچووکی تێدایە — پێش ئەوەی بخوێنیتەوە بیدۆزەرەوە:
total = 0;
n = input('Enter the last number: ');
for i = 1:n
total = total + factorial(n);
end
totalEnter the last number: 4
total =
96The answer should be , but the program prints 96. A (checking with a trace table) shows why: the term never changes, because it uses n (always 4) instead of the loop variable i. The program adds four times.
وەڵامەکە دەبێت بێت، بەڵام 96 چاپ دەکات. (پشکنین بە خشتەی بەدواداچوون) هۆکارەکەی پیشان دەدات: بڕەکە هەرگیز ناگۆڕێت، چونکە n (هەمیشە 4) بەکار دەهێنێت لە جیاتی i. چوار جار کۆ دەکاتەوە.
i | factorial(n) | total (wrong)total (هەڵە) | factorial(i) | total (right)total (دروست) |
|---|---|---|---|---|
| 1 | 24 | 24 | 1 | 1 |
| 2 | 24 | 48 | 2 | 3 |
| 3 | 24 | 72 | 6 | 9 |
| 4 | 24 | 96 | 24 | 33 |
An alternating series: J = -Jزنجیرەیەکی ئاڵوگۆڕ: J = -J
Some series change sign: plus, minus, plus, minus. The first lab program does this with a sign variable J that starts at 1 and is flipped with J = -J at the end of every turn. The loop variable counter runs over the odd numbers , so the program computes
هەندێک زنجیرە نیشانە دەگۆڕن: کۆ، کەم، کۆ، کەم. یەکەم تاقیگە ئەمە بە نیشانەی J دەکات کە بە 1 دەست پێدەکات و لە کۆتایی هەر بە J = -J هەڵدەگەڕێتەوە. counter بەسەر ژمارە تاکەکانی ـدا دەڕوات، بۆیە ئەمە هەژمار دەکات:
n = input('n=');
x = input('x=');
J = 1;
y = 0;
for counter = 1:2:2*n+1
y = y + J*((x^counter)/factorial(counter+1));
J = -J;
end
disp(y);n=2
x=1
0.4597Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
Jholds the sign of the next term.Jنیشانەی بڕی دواتر هەڵدەگرێت.- Lineدێڕی 5
1:2:2*n+1gives 1, 3, 5 when : three turns.1:2:2*n+1بۆ دەبێتە 1، 3، 5: سێ .- Lineدێڕی 7
Flip the sign for the next turn.
نیشانەکە بۆ دواتر هەڵبگەڕێنەوە.
| Turn | counter | J in this turnJ لەم | Term addedبڕی زیادکراو | y after the turny دوای |
|---|---|---|---|---|
| 1 | 1 | 1 | 0.5000 | |
| 2 | 3 | 0.4583 | ||
| 3 | 5 | 1 | 0.4597 |
So . With more terms the sum approaches ; for that is 0.45970, so three terms already give four correct decimals.
کەواتە . بە بڕی زیاتر کۆکە لە نزیک دەبێتەوە؛ بۆ ئەوە 0.45970ـە، بۆیە سێ بڕ پێشتر چوار ژمارەی دروستی دوای دەدەن.
An alternating series: J = -Jزنجیرەیەکی ئاڵوگۆڕ: J = -J
The MATLAB way: the same sum in one lineڕێگای MATLAB: هەمان کۆ لە یەک دێڕدا
MATLAB was built for whole arrays, so a sum like this is often written without a loop: make the vector of all k values, compute every term at once with the element-by-element operators .^, .* and ./, and add them with sum. factorial also works on a whole vector. (The element-by-element operators are taught in array operations and sum in functions for arrays.)
MATLAB بۆ تەواو دروست کراوە، بۆیە کۆیەکی وەک ئەمە زۆرجار بێ دەنووسرێت: هەموو k دروست بکە، هەموو بڕەکان بەیەکەوە بە بە .^، .* و ./ هەژمار بکە و بە sum کۆیان بکەرەوە. factorialـیش لەسەر تەواو کار دەکات. ( بە لە کارەکانی ڕیزەک و sum لە کردارەکانی ڕیزەکدا دەخوێنرێن.)
n = 2; x = 1;
k = 0:n;
y = sum((-1).^k .* x.^(2*k+1) ./ factorial(2*k+2))y =
0.4597Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
kis[0 1 2].kدەبێتە[0 1 2].- Lineدێڕی 3
The three terms are made at once and added.
سێ بڕەکە بەیەکەوە دروست دەکرێن و کۆ دەکرێنەوە.
Both versions are correct. The loop shows each step and is easy to trace; the one-line version is shorter and usually faster in MATLAB. Learn to read both.
هەردوو وەشانەکە دروستن. هەموو هەنگاوێک پیشان دەدات و بەدواداچوونی ئاسانە؛ وەشانی یەک دێڕی کورتترە و لە MATLABـدا زۆرجار خێراترە. فێربە هەردووکیان بخوێنیتەوە.
Trace the loop: lab program 5خولەکە بەدوادا بچۆ: بەرنامەی پێنجی تاقیگە
Some programs are best understood with pencil and paper. Trace this lab program for , before you look at the output: write one row per turn with counter, b and y.
لە هەندێک بە قەڵەم و کاغەز باشتر تێدەگەیت. پێش ئەوەی سەیری بکەیت، ئەم تاقیگە بۆ ، بەدوادا بچۆ: بۆ هەر دێڕێک بنووسە بە counter، b و y.
n = input('n=');
x = input('x=');
y = 0;
b = n;
for counter = 1:2:2*n+1
y = y + 1 + (sin(x^b))^counter/factorial(counter)
b = n + 1;
end
disp(y);n=1
x=1
y =
1.8415
y =
2.9408
2.9408Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 6
No semicolon:
yis printed in every turn.نییە:
yلە هەموو چاپ دەکرێت.- Lineدێڕی 7
bchanges only once: fromnton + 1, and then it staysn + 1.bتەنها جارێک دەگۆڕێت: لەnبۆn + 1و دوای ئەوەn + 1دەمێنێتەوە.
| Turn | counter | b | Termبڕ | y |
|---|---|---|---|---|
| 1 | 1 | 1 | 1.8415 | |
| 2 | 3 | 2 | 2.9408 |
The output is 2.9408. Name three things in the code that look unintended.
2.9408ـە. سێ شت لە کۆدەکەدا ناو ببە کە وا دیارە مەبەست نەبوون.
Show answerوەڵامەکە پیشان بدە
bisnin the first turn andn + 1in every later turn — a variable that changes only once probably belongs before the loop, or should depend oncounter.y + 1 + …adds 1 in every turn, so the result grows by the number of turns; a series usually adds only the term.- The missing
;prints every middle value ofy— useful for tracing, noisy in a finished program.
bلە یەکەمداnو لە هەموو دواترداn + 1ـە — کە تەنها جارێک بگۆڕێت لەوانەیە پێش بێت، یان دەبێت پەیوەست بێت بەcounter.y + 1 + …لە هەموو 1 زیاد دەکات، بۆیە ئەنجامەکە بە ئەندازەی ژمارەی گەورە دەبێت؛ زنجیرە بە زۆری تەنها بڕەکە زیاد دەکات.;ـی کەم هەموو ناوەڕاستیyچاپ دەکات — بۆ بەدواداچوون بەسوودە، لە تەواوبوودا ژاوەژاوە.
Because the lab sheet does not state the series, the program's intention cannot be known for sure; tracing is how you find out what code really does.
لەبەر ئەوەی پەڕەی تاقیگەکە زنجیرەکە نانووسێت، مەبەستی بە دڵنیاییەوە نازانرێت؛ بەدواداچوون ڕێگای زانینی ئەوەیە کە کۆد بەڕاستی چی دەکات.
Searching while looping: largest and smallestگەڕان لە کاتی خولانەوەدا: گەورەترین و بچووکترین
A loop can also search. A lab program reads five numbers and keeps the largest and the smallest seen so far — the same idea as the largest of three algorithm, now with a loop. The key line is the start: maxi and mini both begin as the first number. Then the loop reads numbers 2 to 5 and replaces a record whenever a new number beats it:
دەتوانێت بگەڕێتیش. تاقیگە پێنج ژمارە دەخوێنێتەوە و گەورەترین و بچووکترینی تا ئێستا بینراو هەڵدەگرێت — هەمان بیرۆکەی گەورەترینی سێ ژمارە، ئێستا بە . دێڕە گرنگەکە سەرەتاکەیە: maxi و mini هەردووکیان بە یەکەم ژمارە دەست پێدەکەن. پاشان ژمارەکانی 2 تا 5 دەخوێنێتەوە و هەر کاتێک ژمارەیەکی نوێ ڕیکۆردێک تێپەڕێنێت، دەیگۆڕێت:
number = input('First number: ');
maxi = number;
mini = number;
for i = 2:5
number = input('Next number: ');
if maxi < number
maxi = number;
end
if mini > number
mini = number;
end
end
maxi
miniFirst number: 4
Next number: 9
Next number: -1
Next number: 7
Next number: 3
maxi =
9
mini =
-1Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2-3
Start from the first number, not from 0.
لە یەکەم ژمارەوە دەست پێبکە، نەک لە 0.
- Lineدێڕی 4
The loop starts at 2 because number 1 has already been read.
لە 2 دەست پێدەکات چونکە ژمارەی 1 پێشتر خوێندراوەتەوە.
- Lineدێڕی 13-14
The names
maxiandminiwisely avoid hiding MATLAB'smaxandmin.ناوەکانی
maxiوminiبە ژیرییەوەmaxوminـی MATLAB ناشارنەوە.
| Turn | number | maxi | mini |
|---|---|---|---|
| startسەرەتا | 4 | 4 | 4 |
| 2 | 9 | 9 | 4 |
| 3 | 9 | ||
| 4 | 7 | 9 | |
| 5 | 3 | 9 |
Why not start maxi at 0? Because for the inputs no number is bigger than 0, and the program would wrongly report 0. Starting from the first input is always safe. The lab's prompts (“give me a newe numbr”) were also corrected. When the numbers are already in a vector, the built-in functions do the search in one call: max([4 9 -1 7 3]) is 9 and min(...) is (functions for arrays).
بۆچی maxi بە 0 دەست پێنەکات؟ چونکە بۆ هیچ ژمارەیەک لە 0 گەورەتر نییە و بە هەڵە 0 ڕادەگەیەنێت. دەستپێکردن لە یەکەم هەمیشە سەلامەتە. تاقیگەکەش («give me a newe numbr») چاک کراونەتەوە. کاتێک ژمارەکان پێشتر لە ، بە یەک بانگکردن گەڕانەکە دەکەن: max([4 9 -1 7 3]) دەکاتە 9 و min(...) دەکاتە (کردارەکانی ڕیزەک).
Decisions inside a loopبڕیاردان لەناو خولێکدا
The body of a loop can hold any commands — also an if or a switch, so each turn can make its own decision. A lab program reads numbers one by one and says whether each is positive, negative or zero (if/elseif/else):
ناوەڕۆکی دەتوانێت هەر هەڵبگرێت — if یان switchـیش، بۆیە هەر دەتوانێت بڕیاری خۆی بدات. تاقیگە ژمارەکان یەک یەک دەخوێنێتەوە و دەڵێت هەریەکەیان موجەبە، سالبە یان سفرە (if/elseif/else):
for i = 1:4
number = input(['Number ', num2str(i), ': ']);
if number > 0
fprintf('%g is positive\n', number)
elseif number < 0
fprintf('%g is negative\n', number)
else
disp('0 is zero')
end
endNumber 1: 4 4 is positive Number 2: -2 -2 is negative Number 3: 0 0 is zero Number 4: 5 5 is positive
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
The lab reads 15 numbers (
for i = 1:15); 4 keep the sample run short.تاقیگەکە 15 ژمارە دەخوێنێتەوە (
for i = 1:15)؛ 4 ژمارە نموونەکە کورت دەکەنەوە.- Lineدێڕی 2
The prompt is built from text and
num2str(i), so it shows the turn number.لە دەق و
num2str(i)دروست دەکرێت، بۆیە ژمارەی پیشان دەدات.- Lineدێڕی 4
The lab printed
numberwithout;and thendisp('positive')— two lines per number; onefprintfis tidier.تاقیگەکە
numberـی بێ;چاپ دەکرد و پاشانdisp('positive')— بۆ هەر ژمارەیەک دوو دێڕ؛ یەکfprintfڕێکترە.
Decisions inside a loopبڕیاردان لەناو خولێکدا
A switch inside a loop: three accumulatorsswitch لەناو خولێکدا: سێ گۆڕاوی کۆکردنەوە
Another lab program reads several numbers and finds the sum of the positive ones, the sum of the negative ones and the number of zeros. It uses sign(x), which gives 1, or 0 (sign), as the switch value, and three accumulators. Here it is as given, with its output for the inputs :
تری تاقیگە چەند ژمارەیەک دەخوێنێتەوە و کۆی ، کۆی و ژمارەی سفرەکان دەدۆزێتەوە. sign(x) بەکار دەهێنێت، کە 1، یان 0 دەدات (sign)، وەک switch، لەگەڵ سێ . ئەمە وەک خۆیەتی، لەگەڵ بۆ :
n = input('how many number you want enter:');
s1 = 0;
s2 = 0;
s3 = 0;
ze = 1;
for i = 1:n
n = input('enter numbers: ');
m = sign(n);
switch (m)
case 1
s1 = s1 + n;
case -1
s2 = s2 + n;
case 0
s3 = s3 + ze;
end
end
disp('summation of +ve numbers:'), s1
disp('summation of -ve numbers:'), s2
disp('mumber of zeros:'), s3how many number you want enter:4
enter numbers: 4
enter numbers: -2
enter numbers: 0
enter numbers: 5
summation of +ve numbers:
s1 =
9
summation of -ve numbers:
s2 =
-2
mumber of zeros:
s3 =
1It works, but it is hard to read. n means how many numbers in line 1 and then the current number in line 7. That does not break the loop — 1:n was worked out once, before the first turn (the loop variable belongs to the loop) — but a reader must stop and think. ze is just the number 1, the names s1, s2, s3 say nothing, and the output says “mumber”. The cleaned-up version:
کار دەکات، بەڵام خوێندنەوەی سەختە. n لە دێڕی 1دا واتە چەند ژمارە و پاشان لە دێڕی 7دا واتە ژمارەی ئێستا. ئەمە تێک نادات — 1:n جارێک پێش یەکەم هەژمار کرا (گۆڕاوی خول هی خولەکەیە) — بەڵام خوێنەر دەبێت بوەستێت و بیر بکاتەوە. ze تەنها ژمارە 1ـە، ناوەکانی s1، s2، s3 هیچ نالێن و دەڵێت «mumber». وەشانە ڕێکخراوەکە:
count = input('How many numbers? ');
sum_pos = 0; % sum of the positive numbers
sum_neg = 0; % sum of the negative numbers
zero_count = 0; % how many zeros
for i = 1:count
x = input('Number: ');
switch sign(x)
case 1
sum_pos = sum_pos + x;
case -1
sum_neg = sum_neg + x;
case 0
zero_count = zero_count + 1;
end
end
fprintf('Sum of positive numbers: %g\n', sum_pos)
fprintf('Sum of negative numbers: %g\n', sum_neg)
fprintf('Number of zeros: %d\n', zero_count)How many numbers? 4 Number: 4 Number: -2 Number: 0 Number: 5 Sum of positive numbers: 9 Sum of negative numbers: -2 Number of zeros: 1
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2-4
Three accumulators, all set to 0 before the loop. Never call one
sumorzeros— both are MATLAB functions.سێ ، هەموویان پێش 0 کراون. هەرگیز ناوی یەکێکیان مەنێ
sumیانzeros— هەردووکیان MATLABن.- Lineدێڕی 13
A zero counter just adds 1.
سفر تەنها 1 زیاد دەکات.
A loop inside a loop: filling a tableخولێک لەناو خولێکدا: پڕکردنەوەی خشتەیەک
A runs completely for every turn of the outer loop: for each row i, the inner loop visits every column j. The course guide fills a times table this way. Make the matrix at its final size first, with zeros, and then fill it — this saves MATLAB from growing the matrix again and again, and MathWorks' own for example does the same:
بۆ هەر دەرەوە بە تەواوی جێبەجێ دەبێت: بۆ هەر ڕیزێکی i، ناوەوە سەردانی هەموو ستوونێکی j دەکات. ڕێبەرەکەی وانەکە بەم شێوەیە خشتەیەکی لێکدان پڕ دەکاتەوە. سەرەتا بە zeros بە قەبارەی کۆتایی دروست بکە و پاشان پڕی بکەرەوە — ئەم MATLAB ڕزگار دەکات لە گەورەکردنی جار لە دوای جار و نموونەی forـی خودی MathWorksـیش هەمان کار دەکات:
T = zeros(4, 6); % preallocation: the table first
for i = 1:4 % rows
for j = 1:6 % columns
T(i, j) = i*j;
end
end
TT =
1 2 3 4 5 6
2 4 6 8 10 12
3 6 9 12 15 18
4 8 12 16 20 24Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
zeros(4, 6)makes a matrix of zeros (see ready-made matrices and reaching one element).zeros(4, 6)لە سفر دروست دەکات (بڕوانە ماتریکسەکانی ئامادە و گەیشتن بە یەک توخم).- Lineدێڕی 4
This line runs times.
ئەم دێڕە جار جێبەجێ دەبێت.
The Python track builds patterns and tables with the same shape of loops (nested loops).
بەشی Python بە هەمان شێوەی نەخشە و خشتە دروست دەکات (خولە ناوەکییەکان).
Common mistakesهەڵە باوەکان
| Mistakeهەڵە | What happensچی ڕوودەدات | Fixچارەسەر |
|---|---|---|
An accumulator called sum (or a counter called zeros) بە ناوی sum (یان بە ناوی zeros) | MATLAB's function is hidden until clear sum. MATLAB دەشاردرێتەوە تا clear sum. | total, sum_pos, zero_counttotal، sum_pos، zero_count |
factorial(n) instead of factorial(i)factorial(n) لە جیاتی factorial(i) | Every turn adds the same term.هەموو هەمان بڕ زیاد دەکات. | Use the loop variable in the term.لە بڕەکەدا بەکار بهێنە. |
total = 0 inside the looptotal = 0 لەناو | The total is reset every turn; only the last term is left.کۆکە لە هەموو سفر دەکرێتەوە؛ تەنها دوایین بڕ دەمێنێتەوە. | Set it once, before the loop.جارێک، پێش ، دایبنێ. |
No total = 0 at allهیچ total = 0 نییە | An error, or an old total from the workspace is added to.، یان کۆیەکی کۆن لە زیادی بۆ دەکرێت. | Always start the accumulator yourself.هەمیشە خۆت دەست پێبکە. |
Starting maxi at 0دەستپێکردنی maxi بە 0 | Wrong when all numbers are negative.کاتێک هەموو ژمارەکان سالبن هەڵەیە. | Start from the first number.لە یەکەم ژمارەوە دەست پێبکە. |
for i = 1:n when n was never setfor i = 1:n کاتێک n هەرگیز وەرنەگرتووە | An error, or an old n from the workspace decides the number of turns.، یان nـێکی کۆن لە ژمارەی خولەکان دیاری دەکات. | Read or set n before the loop.پێش n بخوێنەوە یان دایبنێ. |
| Looping over a column vectorخولانەوە بەسەر ستوونیدا | Only one turn, with the whole column.تەنها یەک ، بە هەموو ستوونەکەوە. | for x = v'for x = v' |
| Changing the loop variable inside the body to skip turnsگۆڕینی لەناو ناوەڕۆکدا بۆ تێپەڕاندنی | No effect on the next turn.هیچ کاریگەرییەکی لەسەر دواتر نییە. | Choose the right vector (1:2:9), or use a while loop. دروست هەڵبژێرە (1:2:9)، یان خولی while بەکار بهێنە. |
Practiceڕاهێنان
Add with a loop and check the answer with the formula .
بە کۆ بکەرەوە و وەڵامەکە بە بپشکنە.
Show answerوەڵامەکە پیشان بدە
total = 0;
for k = 1:10
total = total + k^2;
end
total
check = 10*11*21/6total = 385 check = 385
Compute 6! by multiplying in a loop, without factorial. What must the accumulator start at?
6! بە لێکدان لەناو هەژمار بکە، بێ factorial. دەبێت بە چی دەست پێبکات؟
Show answerوەڵامەکە پیشان بدە
p = 1; % a product starts at 1, not 0
for k = 1:6
p = p*k;
end
pp = 720
A sum starts at 0; a product starts at 1. Do not call it prod — that is also a MATLAB function.
کۆ بە 0 دەست پێدەکات؛ لێکدان بە 1. ناوی مەنێ prod — ئەوەش MATLABـە.
Compute with a sign variable that flips (J = -J), and compare with pi.
بە نیشانە کە هەڵدەگەڕێتەوە (J = -J) هەژمار بکە و لەگەڵ pi بەراوردی بکە.
Show answerوەڵامەکە پیشان بدە
total = 0;
J = 1;
for k = 0:99
total = total + J/(2*k + 1);
J = -J;
end
approx = 4*totalapprox =
3.1316100 terms give 3.1316 — still 0.01 from . This series is famous but slow.
100 بڕ 3.1316 دەدەن — هێشتا 0.01 لە دوورە. ئەم زنجیرەیە ناسراوە بەڵام هێواشە.
Add in a loop and compare with exp(1).
لەناو کۆ بکەرەوە و لەگەڵ exp(1) بەراوردی بکە.
Show answerوەڵامەکە پیشان بدە
total = 0;
for k = 0:10
total = total + 1/factorial(k);
end
format long
total
exp(1)
format defaulttotal = 2.718281801146385 ans = 2.718281828459046
Eleven terms agree with e to 7 decimals. (format long shows more digits; see display formats.)
یازدە بڕ تا حەوت ژمارەی دوای لەگەڵ e یەک دەگرنەوە. (format long ژمارەی زیاتر پیشان دەدات؛ بڕوانە شێوەکانی پیشاندان.)
The course guide shows a loop that subtracts each row from the next one. Trace this version with new numbers and write the final matrix: A = [2 1 3; 4 1 5; 6 2 7]; for j = 2:3, A(j,:) = A(j,:) - A(j-1,:); end
ڕێبەرەکەی وانەکە پیشان دەدات کە هەر ڕیزێک لە ڕیزی دواتر کەم دەکاتەوە. ئەم وەشانە بە ژمارەی نوێ بەدوادا بچۆ و بنووسە: A = [2 1 3; 4 1 5; 6 2 7]; for j = 2:3, A(j,:) = A(j,:) - A(j-1,:); end
Hintئاماژە
A(j,:) means the whole row j. Write the matrix after each turn.
A(j,:) واتە هەموو ڕیزی j. دوای هەر بنووسە.
Show answerوەڵامەکە پیشان بدە
Turn : row 2 becomes . Turn : row 3 becomes — it uses the new row 2.
: ڕیزی 2 دەبێتە . : ڕیزی 3 دەبێتە — ڕیزی 2ـی نوێ بەکار دەهێنێت.
A = [2 1 3; 4 1 5; 6 2 7];
for j = 2:3
A(j,:) = A(j,:) - A(j-1,:);
end
AA =
2 1 3
2 0 2
4 2 5Read 6 marks with a loop and print how many are 50 or more and the highest mark.
بە شەش نمرە بخوێنەوە و چاپ بکە چەندیان 50 و سەرووترن و بەرزترین نمرە چەندە.
Hintئاماژە
A counter and a running maximum in the same loop; start the maximum from the first mark.
و گەورەترینێکی بەردەوام لە هەمان ؛ گەورەترین لە یەکەم نمرەوە دەست پێبکە.
Show answerوەڵامەکە پیشان بدە
passed = 0;
best = input('Mark 1: ');
if best >= 50
passed = passed + 1;
end
for i = 2:6
m = input(['Mark ', num2str(i), ': ']);
if m >= 50
passed = passed + 1;
end
if m > best
best = m;
end
end
fprintf('%d marks of 50 or more; highest %g\n', passed, best)Mark 1: 45 Mark 2: 72 Mark 3: 50 Mark 4: 38 Mark 5: 91 Mark 6: 66 4 marks of 50 or more; highest 91
Summaryکورتە
for k = v … endruns the body once for each value of the row vectorv: ranges, countdowns and lists all work; a column vector gives one turn.- The loop variable gets the next value at the start of each turn; changes inside the body do not skip turns.
- An accumulator starts at 0 (a product at 1) before the loop and grows by one term per turn; never name it
sum. - Use the loop variable in the term (
factorial(i), notfactorial(n));J = -Jmakes signs alternate. - Trace tables reveal what a loop really does; the same sum can often be written in one line with
.^,./andsum. - Searching: start the maximum and minimum from the first value; decisions (
if,switch) can sit inside a loop. - Nested loops fill tables; preallocate with
zerosfirst.
for k = v … endناوەڕۆکەکە بۆ هەر ڕیزییvجارێک جێبەجێ دەکات: زنجیرە، ژماردنی بەرەو خوار و لیست هەموویان کار دەکەن؛ ستوونی یەک دەدات.- لە سەرەتای هەر دواتر وەردەگرێت؛ گۆڕانکاری لەناو ناوەڕۆکدا تێناپەڕێنێت.
- پێش بە 0 دەست پێدەکات (لێکدان بە 1) و لە هەر بە یەک بڕ گەورە دەبێت؛ هەرگیز ناوی مەنێ
sum. - لە بڕەکەدا بەکار بهێنە (
factorial(i)، نەکfactorial(n))؛J = -Jنیشانەکان ئاڵوگۆڕ دەکات. - ئاشکرای دەکەن بەڕاستی چی دەکات؛ هەمان کۆ زۆرجار بە
.^،./وsumلە یەک دێڕدا دەنووسرێت. - گەڕان: گەورەترین و بچووکترین لە یەکەم دەست پێبکە؛ بڕیار (
if،switch) دەتوانێت لەناو بێت. - خشتە پڕ دەکەنەوە؛ سەرەتا بە
zerosبکە.
What does for k = 4:-1:1 do with k?for k = 4:-1:1 چی بە k دەکات؟
It takes 4, 3, 2, 1 — four turns, counting down.
دەبێتە 4، 3، 2، 1 — چوار ، بەرەو خوار.
Why must total = 0 come before the loop?بۆچی دەبێت total = 0 پێش خولەکە بێت؟
Inside the loop it would wipe the running total in every turn.
لەناو لە هەموو کۆی بەردەوام دەسڕێتەوە.
The lab's factorial(n) program gives 96 for . What should it give, and why?بەرنامەی factorial(n)ـی تاقیگە بۆ ئەنجامی 96 دەدات. دەبێت چی بدات و بۆچی؟
. The term must use i, which changes every turn.
. بڕەکە دەبێت i بەکار بهێنێت، کە لە هەموو دەگۆڕێت.
Lesson complete!وانەکە تەواو بوو!
Well done. Review the key terms, then go on to the next lesson.دەستخۆش. سەیرێکی زاراوە سەرەکییەکان بکەرەوە، پاشان بڕۆ بۆ وانەی داهاتوو.
Key termsزاراوە سەرەکییەکان
while Loops, break and continueخولەکانی while، break و continue
Related lecturesوانە پەیوەندیدارەکان
- Making Decisions: Relational Operators and if / elseif / elseبڕیاردان: کارپێکەرەکانی بەراوردکردن و if / elseif / else
- Script Files, input, disp and fprintfفایلەکانی دەسنووس، input، disp و fprintf
- Algorithms, Pseudocode and Flowchartsئەلگۆریزمەکان، نیمچەکۆد و هێڵکارییەکانی ڕەوت
- Subscripts and Sigma (Σ) Notationژێرنووسەکان و نیشانەی سیگما (Σ)
- Exponential Functions and the Number eنەخشە توانییەکان و ژمارەی e
- The for Loop and range()خولی for و
range() - Nested Loops and Patternsخولە ناوەکییەکان و کێشانی شێوە
- while Loops, break and continueخولەکانی while، break و continue
- Functions for Arraysکردارەکانی ڕیزەک
- Matrix Operations vs Element-by-Element Operationsکارەکانی ماتریکس بەرامبەر کارەکانی توخم بە توخم
References and further readingسەرچاوەکان و خوێندنەوەی زیاتر
This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.