Clear Filters
Clear Filters

Script writing: using the "for loop" in matrices?

3 views (last 30 days)
I'm writing script for an assignment and I feel completely lost. I've watched all the videos my professor provided and have spent far too long reading the matlab help guide and it's just not clicking in my brain. Can someone explain this process to me?
I need to write a script for a matrix that is 1x100 of even numbers from 2 too 200.
What would n and s be for the for loop? How would I even make a matrix that uses a for loop?
Thank you

Answers (1)

John Chilleri
John Chilleri on 3 Mar 2017
You can use a for loop to fill in the elements of a matrix. In your case, you are dealing with a 1 x 100 matrix, which is usually referred to as a vector.
It's often efficient to preallocate your matrix, that is, initialize its size:
m = zeros(1,100);
in the above line, I create a variable m which is size 1 x 100 and each element is 0.
Now, I can loop through the contents and set the elements equal to the even values.
for i = 1:100
m(i) = 2*i;
The above loop runs for i = 1,2,3,...,100 and it sets the elements each time it runs through a value.
So when i = 1, m(i) = m(1) which is the first element of m, and then we set that element equal to 2*i which is 2*1 = 2. Then, i = 2, m(2) is second element, and we set that equal to 2*i = 2*2 = 4. You can see that this will continue until i = 100 and we set the 100th element of m, (m(100), to 2*i = 2*100 = 200.
You'll find that there are more efficient ways to create the matrix, such as
m = (2:2:200);
m = 2*(1:100);
but make sure you only use what you understand.
Hope this helps!


Find more on Loops and Conditional Statements in Help Center and File Exchange


Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!