Info

This question is closed. Reopen it to edit or answer.

How to struct ?

1 view (last 30 days)
xoxox
xoxox on 13 Feb 2018
Closed: MATLAB Answer Bot on 20 Aug 2021

HI, can anyone tell me is this correct?

Tagprice = 1:6000;
if  Tagprice < 200
D = 0;
C = 0.25;
E = 0.14;
Price_D(Tagprice)=Tagprice*(1-D);
Store.Item1.Tag_price=Tagprice ;
Store.Item1.Price_after_discount=Tagprice*(1-D);
Price_C(Tagprice)=Tagprice*(1-C);
Store.Item2.Tag_price=Tagprice ;
Store.Item2.Price_after_discount=Tagprice*(1-C);
Price_E(Tagprice)=Tagprice*(1-E);
Store.Item3.Tag_price=Tagprice ;
Store.Item3.Price_after_discount=Tagprice*(1-E);
end

Answers (1)

Eric
Eric on 19 Feb 2018
Edited: Eric on 19 Feb 2018
It's not quite right, but you're on the right track. First, you should have TagPrice = 1:200:7000, according to the question. Second, the conditional at the top is not doing what you probably intended it to do... remove it. Once you do these things, you can use conditional indexing to set the discount for each of the different price ranges for each item. Right now you are using the same discount (namely the first) for each item, regardless of price. For example, the most straightforward approach for Item 1 would look something more like:
Store.Item1.Tag_price = TagPrice;
DiscountPrice = TagPrice;
DiscountPrice(200<=TagPrice & TagPrice<600) = (1-0.015).*TagPrice(200<=TagPrice & TagPrice<600);
DiscountPrice(600<=TagPrice & TagPrice<1200) = (1-0.03).*TagPrice(600<=TagPrice & TagPrice<1200);
.
.
.
Store.Item1.Price_after_discount = DiscountPrice;
The vertical ellipsis would be filled in according to each price range in the table, and you would repeat this whole thing for all 3 items. Obviously, this is not the best/neatest/most adaptable/most efficient approach and it can be by using things like for loops, a vector of price boundaries, a matrix of discounts, indexing your structure (e.g. Store.Item(2)), etc. Since this looks like a homework question, I'll leave it to you to figure out how to improve your code with these suggestions, although you can always ask another question if you get stuck.
  1 Comment
Guillaume
Guillaume on 19 Feb 2018
When you write the same (or near identical) line of code twice in a row you should always think of a better alternative. In this case, a call to discretize combined with a 6x3 matrix of discount would avoid all the ellipses.
discounts = [0 25 14;1.5 30 19;3 35 24;4.5 50 30;7 60 36;10 70 45];
tagprice = (1:200:7000).';
discountidx = discretize(tagprice, [0 200 600 1200 2600 6000 Inf]);
discountprice = tagprice .* (1 - discounts(discountidx, :)/100); %assumes R2016b or later for implicit expansion
%neater display than a structure:
[table(tagprice), array2table(discountprice, 'VariableNames', compose('Item%d', size(discounts, 2)))]

Tags

Community Treasure Hunt

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

Start Hunting!