In: Computer Science
I am learning Matlab.
I have a math formula such as A(x , y)= (x+1) / (y+1), and n=6
How can I write down the for loop in Matlab to express 1 <= x and y < = n?
Thanks
Use of for loop is important aspect and we must also learn applying condtions.
See the code below that will help you understand concepts:
n= 5;
A = zeros(n);% declare a n*n matrix with all values 0
% Now let's fill value using 2 loops i and j
for i = 1:n % loop works for i = 1,2,3 ... n-1,n
for j = 1:n
A(i,j) = (i+1)/(j+1);
end
end % make sure to write end
disp(A); % prints in console window
%see how to apply conditions
% let's set all the values greater than 1 to 200 with i = 2 or 4
for i = 1:n
for j=1:n
% see how to use OR , AND condition and if condition
% we want( i = 2 or i =4) and A(i,j)>1
if(((i == 2)||(i==3))&&(A(i,j)>1))
A(i,j) = 200;
end
end
end
disp(A);
Code screenshot:
Code output:
===============
Explanation :
The if condition is generally used to check certain conditions and based on them it executes the statement below it. t can be followed by else part, which is executed when if condition fails.
Here is the same code that uses while loop instead of for loop. It is also important to understand while loop working.
n= 5;
A = zeros(n);% declare a n*n matrix with all values 0
% Now let's fill value using 2 loops i and j
i=1;
while(i<=n) % loop till i<n
j = 1;
while(j<=n)
A(i,j) = (i+1)/(j+1);
j=j+1; % increment j to move to next column
end
i = i+1;
% increment i to move to next row
end % make sure to write end
disp(A); % prints in console window
Code Screenshot:
Code output:
Note that they have same output. We just performed the same task using while loop instead of for loop.
If you still have any doubts please comment.