MATLAB for Loop Examples

A MATLAB for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.

The MATLAB for loop syntax is given as

for index = values
 <program statements>
 ...
end

MATLAB for loop Examples

1. Write a program to display numbers from 1 to 5.

for p = 1:1:5
   disp(p)
end

Result

2. Write a program to display values which are decrementing by 0.8 at each step. The series start at 9 and end at 6.

for p = 9:-0.8:6
   disp(p)
end

Result

3. Write a program to display the following pattern.

matlab for loop example

p=input('enter row number = ')%enter row number to generate pattern upto that row
x = [];
for i = 1 : p
    x = strcat(x,'*');
    disp(x)
end

Result

4. Write a program to display the following pattern.

p=input('enter row number = ')%enter row number to generate pattern upto that row
x = [];
for i = 1 : p
    x = strcat(x,'*');
    s = [blanks(p-i) x];
    disp(s)
end

Result

5. Write a program to display the following pattern.

n=input('enter row number = ')%enter row number to generate pattern upto that row
for i=n+1:-1:2
  for j=i-1:-1:1
    fprintf('*');
  end
  fprintf('\n');
end

Result

6. Write a program to sum all 1, 2, and 3 digit prime numbers

Method-1

total = 0;
for k = 1:999
  if(isprime(k))
   total = total + k;
  end
end
disp(total)

Method-2

total = 0;
for k = primes(999)
    total = total + k;
end
disp(total)

Result

76127

7. Write a program to duplicating each element of a vector. For example, given the vector [1 4 3], we want to end up with [1 1 4 4 3 3].

Method-1

V = 1:5; % sample vector
for j = 1:length(V)
V2((2*j-1):(2*j)) = V(j);
end
disp(V2)

Method-2

V = 1:5; % sample vector
for j = 1:(2*length(V))
V2(j) = V(ceil(j/2));
end
disp(V2)

Method-3

V = 1:5; % sample vector
counter = 0.5;
for j = 1:(2*length(V))
V2(j) = V(ceil(counter));
counter = counter + 0.5;
end
disp(V2)

Result

8. Write a program that finds all 4 digit twin primes (numbers separated by two that are both primes)

for x = 1001:2:9997
if(isprime(x) & isprime(x+2))
fprintf('%0f and %0f are both prime\n',x,x+2)
end
end

Result

.

.

.

.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

error: Content is protected !!

Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need fund to operate the site, and almost all of it comes from our online advertising.

Please add electricalvoice.com to your ad blocking whitelist or disable your adblocking software.

×