필터 지우기
필터 지우기

Error when looping over an object array

조회 수: 1 (최근 30일)
Astrik
Astrik 2016년 8월 29일
편집: per isakson 2016년 8월 29일
I have created two classes: a market and a good. I can add goods to market by buying them or I can remove them from my market by selling them. I have written a method buy
1. Every time I buy a good, it checks whether there is such a product in my market, and if yes, it adds the quantity to the existing quantity.
2. If the product does not exist, it adds it as a new object to my good array.
function buy(obj, item)
exists=0;
for i=1:length(obj.goods)
if obj.goods(i).name==item.name
obj.goods(i).quantity=obj.goods(i).quantity+item.quantity;
exists=1;
end
end
if exists==0
obj.goods(end+1)=item;
end
end
First time I call the method it adds the object to the array. Now I have only one object in the array.
Second time I get the following error
>> mymarket.buy(cheese)
Error using ==
Matrix dimensions must agree.
Error in market/buy (line 17)
if obj.goods(i).name==item.name
Any help will be appreciated.

채택된 답변

per isakson
per isakson 2016년 8월 29일
편집: per isakson 2016년 8월 29일
Your code cannot compare names of different lengths
>> 'aaa' == 'bbbb';
Error using ==
Matrix dimensions must agree.
>>
Replace
obj.goods(i).name==item.name
by
strcmp( obj.goods(i).name, item.name )

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by