got an error message
이전 댓글 표시
i wrote the following code:
a.name=[];
a.age=[];
a.sex=[];
a.ID=[];
a.GPA=[];
a.name={'bahar';'maryam';'ronia';'kaihan';'vahid';'werya';'hana'};
a.age={2;11;21;18;37;38;25}
a.sex={'f'; 'f'; 'f'; 'f'; 'm'; 'm'; 'm'}
a.ID={1234;11344;11344;98764;34786;12984;45295}
a.GPA={11;12;14;17;19;20;13}
for i=1:7
if a(i).ID==a(i+1).ID
a(i+1).ID=[];
end
end
but i have got this error message:
Index exceeds matrix dimensions.
Error in student11 (line 12)
if a(i).ID==a(i+1).ID
I dont know why? would you please help me?
댓글 수: 2
a is a scalar structure, so clearly a(2), etc, do not exist.
Ganesh Hegade
2017년 8월 2일
You can use like this. But if you want to delete the duplicate ID's after each loop then below code will not work.
for i=1:6
if a.ID{i} == a.ID{i+1}
a.ID{i+1}=[];
end
end
채택된 답변
추가 답변 (1개)
Steven Lord
2017년 8월 2일
99 (or let's go with 9 to save some time) bottles of beer on the wall. 9 bottles of beer.
bottlesOfBeerOnTheWall = 1:9
Take one down, pass it around, 8 bottles of beer on the wall.
8 bottles of beer on the wall, 8 bottles of beer. Take one down, pass it around, 7 bottles of beer on the wall.
etc.
for k = 1:9
bottlesOfBeerOnTheWall(k) = []
end
We receive an error when we try to remove the sixth bottle. Note that we have not removed bottles 1, 2, 3, 4, and 5 at that point but have removed bottles 1, 3 (the new second bottle, once bottle 1 was removed), 5 (the new third bottle after 1 and 3 are gone), 7 (the new fourth bottle), and 9 (the new fifth bottle.)
If you're iterating through an array and deleting elements, there are a couple alternatives you can use to avoid this problem.
- Don't delete as you go. Create a vector (of linear or logical indices) of elements to be deleted then delete them all after you've finished iterating through the whole array.
bottlesOfBeer = [1 2 3 3 4 5 5 6];
shouldBeDeleted = false(size(bottlesOfBeer));
for k = 2:length(bottlesOfBeer)
if bottlesOfBeer(k-1) == bottlesOfBeer(k)
shouldBeDeleted(k) = true;
end
end
bottlesOfBeer(shouldBeDeleted) = []
- Start at the end and work your way forward.
bottlesOfBeerOnTheWall = 1:9
for k = 9:-1:1
bottlesOfBeerOnTheWall(k) = []
end
- Use an approach that avoids iterating. In this case, since you want to compare the diff-erence between adjacent elements, use diff.
bottlesOfBeer = [1 2 3 3 4 5 5 6];
sameAsPrevious = [false diff(bottlesOfBeer)==0]
bottlesOfBeer(sameAsPrevious) = []
카테고리
도움말 센터 및 File Exchange에서 Assembly에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!