MATLAB Answers

How do you store all return values from a while loop in a vector in matlab ?

3 views (last 30 days)
Harshita Jain
Harshita Jain on 26 Apr 2016
Edited: jgg on 27 Apr 2016
I have this for now, but unfortunately it only stores the latest value of choice_breakfast.
while breakfast_choicerep == 'Y' || breakfast_choicerep == 'y'
choice_breakfast = menu('What do you eat for breakfast?',breakfast_items);
vector_choice_breakfast = [choice_breakfast]
breakfast_choicerep = input('Did you eat anything else for brekfast? (Y/N): ', 's');
end

  0 Comments

Sign in to comment.

Answers (1)

jgg
jgg on 26 Apr 2016

You can just store it as a vector:

 vector_choice_breakfast  = cell(1000,1);
 count = 1;
 while breakfast_choicerep == 'Y' | breakfast_choicerep == 'y'
    choice_breakfast = menu('What do you eat for breakfast?',breakfast_items);
    vector_choice_breakfast(count) = choice_breakfast;
    count = count + 1;
    breakfast_choicerep = input('Did you eat anything else for brekfast? (Y/N): ', 's');
end

The only issue is that you have to make sure you handle what happens when more than 1000 breakfast items are eaten, which could involve throwing an error and handling it (say by resizing the vector) or simply disallowing more output.

  4 Comments

Show 1 older comment
Harshita Jain
Harshita Jain on 27 Apr 2016
I get an error saying "Conversion to cell from double is not possible." for the line vector_choice_breakfast(count) = choice_breakfast; I don't understand why it's saying that..
Harshita Jain
Harshita Jain on 27 Apr 2016
The vector_choice_breakfast = cell(1000,1); is what's causing the error. so i just left it as an empty array to begin with: vector_choice_breakfast = []; But now, it's not adding the first value i calculate for choice_breakfast before i started the while loop.
jgg
jgg on 27 Apr 2016
Try changing the brackets in the assignment instead:
vector_choice_breakfast{count} = choice_breakfast;
I thought you were saving character arrays, not floats.

Sign in to comment.