How to Create a Simple Vector in MATLAB?

  • Thread starter Thread starter sara_87
  • Start date Start date
  • Tags Tags
    Matlab
Click For Summary
SUMMARY

The discussion focuses on creating a simple vector in MATLAB, specifically generating a vector t(i) where t(i) = i for i = 1:10. The initial attempt resulted in an unexpected output of 11 elements due to a pre-existing definition of the variable t. The solution provided includes clearing the variable with the command clear t before the loop or using vectorized code t = 1:10; for a more efficient approach.

PREREQUISITES
  • Basic understanding of MATLAB syntax and commands
  • Familiarity with for-loops in programming
  • Knowledge of vectorized operations in MATLAB
  • Experience with variable management in MATLAB
NEXT STEPS
  • Explore MATLAB's vectorization techniques for performance optimization
  • Learn about the clear command and its impact on variable scope
  • Investigate MATLAB's built-in functions for array creation
  • Study best practices for managing variables in MATLAB scripts
USEFUL FOR

Students, educators, and professionals working with MATLAB who need to efficiently create and manage vectors in their programming tasks.

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 ·
Replies
1
Views
2K
  • · Replies 1 ·
Replies
1
Views
3K
Replies
2
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 13 ·
Replies
13
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 10 ·
Replies
10
Views
2K
Replies
2
Views
2K
  • · Replies 20 ·
Replies
20
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K