Need help with calling on a variable as input for a function
Show older comments
I am trying to input a variable from the workspace into my function, but am having trouble. I want to run this code numerous times for the different variables, but only want to input a number for the variable. So, my variables are something like A_1_1, A_1_2, ..., A_1_n (where n is the number of variables) and I want to do myfunction(3,1) for example to call on A_1_3. This is necessary because I have other data in the workspace that I want to call on that is named A_5_1, A_5_2, and so on.
I have tried stringing it all together by converting the numbers input into the function into strings and concatenating, and then using eval and genvarname, but this results in an error when I run it as a function (though not when I run it outside of the function). So my code is something like:
function [a, b] = myfunction(n1,n2)
firststr = strcat('myvar_',num2str(n2));
secondstr = strcat(firststr,'_');
m = strcat(secondstr,num2str(n1));
red = [eval(genvarname(m),'=m')];
which results in the error "The expressionn to the left of the equals sign is not a valid target for an assignment" on line 5 in the above code. This error is not given if I run the same code outside of the function and put in the numbers wanted instead of n1 and n2. (red is created as desired this way). Is there a clear reason as to why it doesn't work in the function, or should I try and avoid using eval?
If the latter, I still need help. I have already tried avoiding using eval as many people have suggested to do so on the internet. I have tried loading the data in as a structure, but am not savvy enough to do so without encountering more errors. I have the data file 'datafile.mat' which contains all of the A_1_1, A_1_2,..., A_1_n variables. How can I load it in as a structure and then access the wanted variables as described above? So I can avoid using eval and the messy way of creating variables from strings to call on them.
Accepted Answer
More Answers (0)
Categories
Find more on Variables 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!