Clear Filters
Clear Filters

How to access a cell array in a function from inside a separate class

2 views (last 30 days)
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?

Answers (1)

Suraj
Suraj on 31 Mar 2023
Edited: Suraj on 31 Mar 2023
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

Categories

Find more on Animation in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!