How to create a new variable for each iteration of a while loop?

23 views (last 30 days)
I am creating a library of books on matlab using a while loop. In the loop the user is asked for a title, author and number of pages. The user is then asked what would they like to do, and if they write add book, a new title author and number of pages should be given. This overwrites the original title author and number of pages and when typing list books, there is only every 1 book to list as only one exists. Obviously title_count does not work but that is the kind of thing I am looking for. also obviously the list books will not currently work, but I want to find a way to store them first and then I can figure that out. Here is my code currently;
a = input('What would you like to do: ', 's');
B = []
count = 1;
while true
if strcmp(a,'quit') == 1;
disp('Good-Bye')
return
elseif strcmp(a,'add book') == 1;
title = input('Title: ', 's');
author = input('Author: ', 's');
pages = input('Number of pages: ', 's');
fprintf('%s, %s, %s has been added to the library \n', title, author, pages)
title_count = title;
author_count = author;
pages_count = pages;
count = count + 1;
a = input('What would you like to do: ', 's');
elseif strcmp(a,'list books') == 1;
else
return
end
end
Please help :)
  2 Comments
Andrew Newell
Andrew Newell on 27 Apr 2017
Someone flagged the previous comment as bullying, presumably because of the statement "That would be a really bad idea", but that statement is directed at the idea, not the person. And Stephen followed it up with a lot of useful information. A very helpful comment, I would say.

Sign in to comment.

Answers (1)

Andrew Newell
Andrew Newell on 26 Apr 2017
Edited: Andrew Newell on 26 Apr 2017
Structures are great for this kind of task (see struct). Here is an example script that assumes you have already created a book:
count = numel(book);
a = input('What would you like to do: ', 's');
while ~strcmp(a,'quit')
if strcmp(a,'add book') == 1
count = count + 1;
book(count).title = input('Title: ', 's');
book(count).author = input('Author: ', 's');
book(count).pages = input('Number of pages: ', 's');
fprintf('%s, %s, %s has been added to the library \n', ...
book(count).title, book(count).author, book(count).pages)
elseif strcmp(a,'list books') == 1
disp(book)
else
disp('Options are ''quit'', ''add book'' or ''list books''.')
end
a = input('What would you like to do: ', 's');
end
disp('Goodbye')
If you are starting with a new collection, you could initialize book with:
book = struct.empty;

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!