1

I want to declare array of type integers named sequence.

After a simulation sequence it will look like [1,3,4,59.........n elements]. I do not know the value of n as it is a random integer.

How can I declare sequence as an array of type int? I did like sequence= [1,1] but this did not work out as sometimes only 1 element and then it has 2 instead of 1 element.

2
  • Where are the values of the array coming from? That will make a difference in what functions you can use. Commented Apr 7, 2011 at 18:03
  • Use foo=typecast (foo,'int16') to convert data type of foo from double (default) to int16 type. Alternatively, declare foo as following: foo=int16 ([]). P.S. : You can choose from a variety of data types. Commented Jul 30, 2013 at 18:05

4 Answers 4

2

In cases where you cannot preallocate the array (when you don't know the size of the array in advance), you can use the following method:

sequence = [];
sequence(end+1) = 1;
sequence(end+1) = 3;
sequence(end+1) = 4;
...

Think of this method as treating sequence as a C++ std::vector and sequence(end+1) = 1 is equivalent to sequence.push_back(1).

Sign up to request clarification or add additional context in comments.

Comments

2

The standard format for declaring an array is:

foo = [];

and you can set any element of the array, at any time, and Matlab will resize automatically. For example:

foo = [];
foo(4) = 1

yields

foo = [ 0 0 0 1]

If you don't know how many elements your array needs to hold, you can do as Jacob suggests and simply resize the array every time. However, if this causes bottlenecks in your code (which you can find by using the profile tool in Matlab), you may want to resize less often, and use a placeholder value for the as-yet-unused elements.

Comments

0

You may want to look into the linspace( from, to, numberOfElements ) function.

Comments

0
var=[ val1 val2 val3....valn]
for i=1:numel(var)
result=var(i)
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.