1

I'm trying to write a code that searches a list and matches a term. In this case 'bus' what I am then trying to do is to get the values for distance and time for that method and add them to separate lists. Attached is my code

distanceb = [];
timeb = [];
for i =1:n
 if strcmp(method(i),'bus') == 1
  distanceb = (x(i))
  timeb = time(i)
 end
end    

I can get the values for the x and time but the code seems to overwrite everytime it adds to the list and I get only one answer for distanceb and timeb. Is there a way to add the values to the list without overwriting the previous value?

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
user2423678
  • 43
  • 1
  • 8

1 Answers1

3

You are assigning new values to distanceb and timeb as scalars and not as lists/vectors.
You need to append values:

 distanceb(end+1) = x(i);
 timeb(end+1) = time(i);

A few remarks:

  1. If you know the final size of distanceb and timeb it is best to pre-allocate them and not grow them inside the loop.

  2. It is best not to use i as a variable name in Matlab.

Community
  • 1
  • 1
Shai
  • 111,146
  • 38
  • 238
  • 371
  • Thanks for the help. I was trying to append using the append function earlier but got stuck on the problem. It does make sense now you have pointed out the error. Thanks for the help – user2423678 Oct 20 '13 at 07:39
  • @user2423678 I'm glad you found my answer useful. Please consider "accepting" it by clicking the "V" icon beside it. It would also be nice if you find this answer upvote-worthy. – Shai Oct 20 '13 at 07:46
  • One final question the output of this is in lots of columns (one column for each result) is there a way to get all the outputs into one column? – user2423678 Oct 20 '13 at 08:03
  • @user2423678 you can use `(:)` operator to stack a matrix into a single column. – Shai Oct 20 '13 at 08:07
  • Yes but where do I/would I place this is in the code. Im new at matlab and unsure? Sorry – user2423678 Oct 20 '13 at 08:08