How to access a cell array in a function from inside a separate class
조회 수: 1 (최근 30일)
이전 댓글 표시
I am working on the very beginnings of a program that will eventually be a natural selection simulator. It currently consists of a Plant class and an Animal class, each with properties to determine if they are alive, how much energy they have, and their x and y coordinates. The animal class also has a move method where it moves toward the nearest plant to it and eats it if it is close enough. Finally, I have a NaturalSelection function, which creates two cell arrays to store each individual instance Plant and Animal respecively, fills them out by a user specified initial amount of each, then runs the move function on each animal a user specified amount of times, and makes each organism reproduce or die on a certain user specified interval of these. The issue I am running into is that, in order to find which plant is the closest to a given animal Animal needs access to plants{}, which is in NaturalSelection. When I try to run NaturalSelection, I get the error "Unrecognized function or variable 'plants'." I think this is because Animal cannot access plants{}, but I have no idea how to fix it. Does anyone know what to do?
댓글 수: 1
Stephen23
2023년 3월 11일
"Does anyone know what to do?"
Pass PLANTS as an input argument to the functions that need it.
답변 (1개)
Suraj
2023년 3월 31일
편집: Suraj
2023년 3월 31일
Hi Thomas
It is my understanding that you’d like to modify the “plants” cell array from within the “move” method of your “Animal” class.
To do this, you’ll have to pass the “plants” cell array as an argument to the “move” method. The “move” function will now create a copy of “plants” to work on. You must then return the modified cell array from the function and assign it to “plants” in the calling code.
Below is a code example of this:
% Define the main script
plants = {'Lily', 'Daisy', 'Jasmine'};
disp(plants); % Display the original contents of the cell array
plants = modify_plants(plants); % Call the function to modify the cell array and assign the result to the original variable
disp(plants); % Display the modified contents of the cell array
% Define a function that modifies a cell array
function modified_plants = modify_plants(plants)
% Modify the contents of the cell array
plants{1} = 'Sunflower';
plants{2} = 'Rose';
% Return the modified cell array as an output argument
modified_plants = plants;
end
I hope this helps
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Animation에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!