이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

How to struct ?

조회 수: 1(최근 30일)
xoxox 2018년 2월 13일
마감: MATLAB Answer Bot 2021년 8월 20일

HI, can anyone tell me is this correct?

Tagprice = 1:6000;
if  Tagprice < 200
D = 0;
C = 0.25;
E = 0.14;
Store.Item1.Tag_price=Tagprice ;
Store.Item2.Tag_price=Tagprice ;
Store.Item3.Tag_price=Tagprice ;


Eric 2018년 2월 19일
편집: Eric 2018년 2월 19일
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
Guillaume 2018년 2월 19일
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)))]


Community Treasure Hunt

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

Start Hunting!

Translated by