How to Create a Simple Vector in MATLAB?

  • Thread starter Thread starter sara_87
  • Start date Start date
  • Tags Tags
    Matlab
AI Thread Summary
To create a simple vector in MATLAB where t(i) = i for i = 1:10, the initial attempt resulted in an 11-element vector due to a pre-existing definition of t. Clearing the variable with "clear t" before the loop resolves this issue. An alternative and more efficient method is to use vectorized code, such as "t = 1:10," which avoids the need to clear the variable. This approach is cleaner and leverages MATLAB's capabilities effectively. Using either method will yield the desired vector of 1 through 10.
sara_87
Messages
748
Reaction score
0

Homework Statement



i want to produce a vector t(i) where t(i)=i and i=1:10

Homework Equations





The Attempt at a Solution



for i=1:10
t(i)=i
end

this gives:
1,2,3,4,5,6,7,8,9,10,10

why is it giving me 11 elements? with two 10's?
i just want:
1,2,3,4,5,6,7,8,9,10
 
Physics news on Phys.org
It's possible t was already defined so that even though that part of your script should work, it is not changing the value of t(11). Try clearing the value first:

clear t
for i = 1:10
t(i) = i
end

Alternatively, you can use vectorized code:

t = 1:10;

This is cleaner, takes advantage of what MATLAB can do, and wouldn't require you to clear the variable first.
 
thanks, that works for me.
 

Similar threads

Replies
1
Views
1K
Replies
1
Views
2K
Replies
3
Views
1K
Replies
10
Views
2K
Replies
20
Views
3K
Back
Top