how to find the quantity of the object based on the given data by using if-else loop?

1 view (last 30 days)
hello i want to find the number of the each fruit based on the given data as below by using if-else loop can any body help me with that thank you
Data = apple orange apple grape grape apple banana grape grape orange apple apple apple grape grape
For assisting the development of the program, program is initiated by defining those fruits as listed below:
A = apple O = orange G = grape B = banana
  1 Comment
Jan
Jan on 15 Jun 2015
Edited: Jan on 15 Jun 2015
Please post the input data in valid Matlab syntax, because a pseudo-code like this line demands for some bold guessing:
Data = apple orange apple grape grape apple banana grape grape orange apple apple apple grape grape
There is no "if-else loop" neither in Matlab nor in any other programming language I know. The IF command simply does not start a loop.
The question looks like a homework. Then it is more useful to post, what you have tried so far and ask a specific question.

Sign in to comment.

Answers (1)

Jan
Jan on 15 Jun 2015
Defining 4 different variables to ddefined the categories is a bad idea. So the first thing you need is to combine them in one cell array:
A = 'apple';
O = 'orange';
G = 'grape';
B = 'banana';
Fruit = {A, O, G, B};
Data = {'apple', 'orange', 'apple', 'grape', 'grape', 'apple', 'banana', ...
'grape', 'grape', 'orange', 'apple', 'apple', 'apple', 'grape', 'grape'};
Now the ismember command and histc would solve the problem efficiently. But I assume that you are asked for a loop and an if-else branching. So start with creating a loop over the elements of Data and use strcmp to find out to which category each string belongs.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!