12

How to push a variable in a vector in Matlab?

Something like this:

A = [5 2 3]; push(A, 7); % A = [5 2 3 7] 

Thanks.

2 Answers 2

28

I found the answer.

Use this:

A = [A, 7]; 

Or this:

A(end + 1) = 7; 
Sign up to request clarification or add additional context in comments.

4 Comments

A=[A,4]; Is the most commonly used solution because it easily generalizes to more complex situations. However the first solution will also work if your vector is transposed so both have their strongpoints.
@DennisJaheruddin: can you give an example where the first method will fail?
@naught101 As disadvantage of the first I only mentioned the second generalizes more easily. Suppose you want to append A to the right of A you can simply do: A=[A,A] whilst for the first method you would need to do: A(:,end+1:end+size(A,2)) = A
@naught101 The first will fail when the vector is a vector of structures, and it begins empty; e.g. my_struct.a = 10; all_structs = []; all_structs(end+1) = my_struct;
0

If you want to stack it vertically you can use

A = [A; 7] 

but for this to be executed, A should of same dimentions as next argument. for example if

A=[1,2 3,4] 

you can stack a vector of length 2 in A as

A = [A;5,6] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.