0% found this document useful (0 votes)
3 views4 pages

MATLAB For Loop Examples and Usage

This document provides a MATLAB lesson focused on using for loops to generate random numbers, specifically counting occurrences of the number 3 and displaying messages based on conditions. It includes examples of generating random values, checking conditions, and iterating through arrays. Additionally, it discusses performance comparisons when scaling the number of random values generated.

Uploaded by

takkkie556
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views4 pages

MATLAB For Loop Examples and Usage

This document provides a MATLAB lesson focused on using for loops to generate random numbers, specifically counting occurrences of the number 3 and displaying messages based on conditions. It includes examples of generating random values, checking conditions, and iterating through arrays. Additionally, it discusses performance comparisons when scaling the number of random values generated.

Uploaded by

takkkie556
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

MATLAB Lesson 4

Example

a) Generate 10 random values from 1 to 5. Count the number of 3’s.

For Loop in MATLAB b) Display ‘wow!’ if more than 20% of the random number is 3.
c) Do parts a) and b) with a For Loop.
d) Extend to 10 million random numbers – which method is faster?

% for loop
Answer
clc, clearvars
% draw random numbers by function randi, Max =5, 1 row, 10 col
% for loop, i starts from 1 to 10
for i = 1:10 A = randi(5,1,10)
i
end

% check if the number in Matrix A == 3


A == 3

% for loop
clc, clearvars

% for loop, i starts from 1 to 10 for space equals 2


for i = 1:2:10
i
end
% find the total sum of the logic output
sum(A==3)
% try again c)

clc, clearvars % for loop


clc, clearvars
% draw random numbers by function randi, Max =5, 1 row, 10 col
A = randi(5,1,10)
A = randi(5,1,10)
for i = 1: length(A)
% check if the number in Matrix A == 3 A(i)==3
if sum(A == 3) >= 3 end
disp('wow!!')
end
% for loop
clc, clearvars More examples in For Loop
A = randi(5,1,10)
% define a temp variable num3 and set it equal to zero
num3=0
for i = 1: length(A)
if A(i)==3
num3= num3+1
statement(s);
end
end
end

statement(s) is where you will write any code (such as displaying the output). You can remove the

The way in which you use a for loop is best illustrated with examples.

How to write a basic for-loop


for i=1:1:4
i
end

This is a basic form of the for loop.

How to display values of a vector


x = -5:5;
for i = 1:length(x)
x(i)
end

This iterates through the vector x using the index i up to the length of the vector x (which in this case
will be 11).
How to use an array in a for loop

Let us call our array x

Then
x = [4 10 16 20 24]
for i = 1:1:length(x);
y(i) = 3*x(i)
end

T
array.

x = -5:1:10;
for i = 1:1:length(x)
if x(i)<0
y(i) = 0;
elseif x(i)<5
y(i) = x(i)^2 +3;
else y(i) = 2*x(i);
end
end
N

Here we have an example that is best illustrated

To plot this one,

plot(x,y)
xlabel('x')
ylabel('y')
title('Plot of y(x)')

Common questions

Powered by AI

Using vectorized operations to count occurrences of a specific integer with 'randi' in MATLAB is advantageous because it can evaluate the condition for all elements simultaneously, thus reducing the execution time compared to a 'for loop' which processes each element one at a time. This approach leverages MATLAB's strengths in handling array operations efficiently.

Using the 'randi' function to generate random numbers within a loop involves calling the function multiple times, which adds overhead due to repeated function calls and individual memory allocations. In contrast, generating a complete set of random numbers at once with 'randi' in MATLAB is generally more efficient as it leverages vectorized operations, which are optimized for speed and resource management. It reduces redundant operations and can store all numbers in a single matrix operation, thus decreasing computational time significantly.

Vectorization in MATLAB involves applying operations directly to entire arrays or matrices without explicitly using loops. This often leads to more concise code and can significantly improve execution speed, particularly for large datasets, due to MATLAB's optimization for array operations. In contrast, 'for loops' iterate through each element sequentially, which can be slower, especially for large datasets because of the overhead of repeated indexing and accessing. Thus, vectorization is generally more efficient for large datasets.

When using a 'for loop' to iterate over an array while modifying its elements in MATLAB, careful consideration must be given to avoid creating unintended side effects, such as overwriting values that are yet to be computed or creating dependencies on elements that are modified early in the iteration. A common precaution is to either work with a copy of the array or ensure that modifications are stored separately until all dependent calculations are completed. Not doing so may lead to incorrect computations if later iterations depend on previous values that are updated in place.

To add conditional checks within a 'for loop' in MATLAB for printing 'wow!', first define the condition logic, then implement the loop to evaluate this condition during each iteration. For instance: A = randi(5,1,10); num3 = 0; for i = 1:length(A) if A(i) == 3 num3 = num3 + 1; end end if num3 > 0.2 * length(A) disp('wow!'); end This approach is beneficial because it allows real-time accumulation and evaluation of conditions, enabling dynamic responses based on the data being processed within the loop.

Practical considerations when using MATLAB 'for loops' for plotting include ensuring the computation is complete before plotting, managing memory use, and enhancing plot clarity by labeling axes and titles. For instance, compute values of a polynomial over a desired range and then use 'plot' to visualize: x = -5:0.5:5; y = zeros(size(x)); coeff = [1 0 -3]; for i = 1:length(x) y(i) = polyval(coeff, x(i)); end plot(x, y); xlabel('x-axis'); ylabel('y-axis'); title('Plot of Polynomial Values'); Such practices help in generating clear, interpretable plots that convey accurate information effectively.

Polynomial evaluation using 'for loops' in MATLAB can be optimized by precomputing powers of the variable and storing repeated computations outside the loop to avoid redundant operations. For each value in the range, the loop iterates through polynomial coefficients, multiplying them by the respective power of the variable and accumulating the result for efficiency. For example: coeff = [3, 5, -1]; x = 0:0.1:10; result = zeros(size(x)); for k = 1:length(coeff) result = result + coeff(k) * x.^(k-1); end This reduces overhead and ensures efficient computation over the entire range.

To implement a 'for loop' in MATLAB that calculates and prints the square of each number in a predefined vector, one would first define the vector and then use a 'for loop' to iterate through each element. Within the loop, calculate the square of the current element and display it. For example: numbers = [2, 3, 4]; for i = 1:length(numbers) squared_value = numbers(i)^2; disp(squared_value); end This loop iterates through the vector 'numbers', calculates the square of each element, and outputs it to the console.

A 'for loop' might be more favorable than vectorization when implementing complex conditional logic in MATLAB because it can provide clearer structure and iteration control when conditions vary based on prior computations. For instance, if altering the value of an array element depends on a non-uniform condition that changes dynamically, a 'for loop' facilitates this by checking each element individually. An example is computing a new value for each element based on conditional logic, which may involve different operations for each element that cannot be expressed efficiently in a vectorized manner.

You might also like