How would one access an array within an array, and then delete a certain string from that array?
1 次查看(过去 30 天)
显示 更早的评论
I am tasked with coding a game of MASH, so this means I must have an main array with the 4 category arrays inside:
ACat= [ a b c d]
BCat= [e f g h]
CCat= [i j k l]
AllCats= [ACat BCat CCat]
This creates a 1x12 array
I then generate a random number, and this will be used to delete the string in that index spot
I want to make sure only one of the strings from each "category" is left, but I cannot figure out how to do this
I have
while [numel(AllCats)>4]
if(numel(ACat)>1)
AllCats(:,RandomNumber)= [ ];
RandomNumber = numel(AllCats)-RandomNumber;
if (RandomNumber <1)
RandomNumber = 1;
And this repeats for all categories. I end up with a 1x4 string for AllCats, but it has mulltiple strings from one category. How would I fix this?
1 个评论
dpb
2022-4-29
Don't create different variables with similar but sequenced names; either use multi-dimensional arrays, cell arrays or dynamically-named field names. Then you can address whichever piece needed programmatically independently of the other pieces.
回答(1 个)
Abhishek Chakram
2023-10-4
Hi Ben Reed.
It is my understanding that you want to access and delete a random string from the allcategories array until one from each category is left. Here is a sample code for that:
ACat = {'a', 'b', 'c', 'd'};
BCat = {'e', 'f', 'g', 'h'};
CCat = {'i', 'j', 'k', 'l'};
AllCats = [ACat, BCat, CCat];
% Generate a random number
randomNumber = randi(numel(AllCats));
% Delete a string at the random index
AllCats(randomNumber) = [];
% Check if there are more than one string from any category
while numel(ACat) > 1 || numel(BCat) > 1 || numel(CCat) > 1
% Generate a new random number
randomNumber = randi(numel(AllCats));
% Delete the category of the string at the random index
if randomNumber <= numel(ACat) && numel(ACat)>1
ACat(randomNumber) = [];
elseif randomNumber <= numel(ACat) + numel(BCat) && randomNumber>numel(ACat)&& numel(BCat)>1
BCat(randomNumber - numel(ACat)) = [];
elseif randomNumber <= numel(ACat) + numel(BCat) + numel(CCat) &&randomNumber>(numel(ACat)+numel(BCat))&& numel(CCat)>1
CCat(randomNumber - numel(ACat) - numel(BCat)) = [];
end
% Update the AllCats array
AllCats = [ACat, BCat, CCat];
end
disp(AllCats);
In this example a random index is generated and stored in the variable called “randomNumber”. The corresponding string from the respective category based on the “randomNumber” is then deleted and “AllCats” array is updated.
I hope this answers your question.
Best Regards,
Abhishek Chakram
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!