1

I am trying to add an element to the end of a matrix and i dont know the length of the matrix.

EvantCal = 999*ones(1,2); . . . . %// in a different function EventCal(end + 1) = [1, 3]; %// the numbers are random . . . 

this is the error I get when I run the code:

In an assignment A(I) = B, the number of elements in B and I must be the same.

1
  • 1
    EvantCal (end+1,:) = [1, 3]; Commented Dec 21, 2015 at 10:46

1 Answer 1

1

The error is becasue you a trying to stuff a 1-by-2 matrix (i.e. [1, 3], which is also the B from the error message) into a single element of EventCal (note that the I in the error message is your end+1 which is a single element). Rather try

EventCal(end+1,:) = [1, 3] 

Here the : refers to all the columns which in your case is 2. Hence 1 row (end+1 is a single number) and 2 columns thus exactly matching the dimensions of your 2-by*1* matrix you are trying to append.

Also, if performance isn't a major issue, you can also use matrix concatenation (but this is less efficient than the indexing approach):

EventCal = [EventCal; [1,3]] 
Sign up to request clarification or add additional context in comments.

3 Comments

thanks, this works but not in the way im trying, i need it to go to the next line so it will look like a matrix and not an array
Sorry, just reread the question and saw your initialization. See the edit
@user2336124 no problem, please mark this as correct if it solved your issue.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.