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

4 次查看(过去 30 天)
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

回答(1 个)

John Chilleri
John Chilleri 2017-3-3
Hello,
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;
end
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!

类别

Help CenterFile Exchange 中查找有关 Get Started with MATLAB 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by