Create a unique name for the output variable based on the name of the input variable in matlab

I am making a program in Matlab to analyze the data of some biomedical data that I have collected. The calculations are very simple but repeatable, so I am interested in writing a small program. I have one matrix (200 x 99) per patient, which is stored in a variable with the name of the patient. I created a function that results in an output variable (finalresult) containing everything I need from this patiรซnts matrix.

I would really like this output variable to bear the name of my input variable. Thus, I can simply call the function for each patient separately, and then collect a list of variables in the workspace instead of manually changing the name of the output variable after each function call.

I hope you understand what I would like to achieve. This is a simplified example of my code:

function [ finalresult] = total_analysis( patientname) first = patientname(:,1)*2; second = first; finalresult = vertcat(first,second); end 

=> output variable name is always finalresult

BUT I would like it to be a unique other "output variablename , preferably finalresult_patientname or patient name

+4
source share
4 answers

why not return the structure with the result and patient name?

 function [ finalresult] = total_analysis( patientname) first = flexion(:,1)*2; second = first; finalresult.data = vertcat(first,second); finalresult.name = patientname; end 
+1
source

I would suggest using a structure array in matlab that stores all your data in one variable:

  s(1).name = 'Jane'; % Store patient name here as a string s(1).data = janesData; % Store patient data s(1).result = total_analysis( s(1).data ) % Store the analyzed data s(2).name = 'John'; % Store patient name here as a string s(2).data = johnsData; % Store patient data s(2).result = total_analysis( s(2).data ) % Store the analyze 

And so on for all your patient data. Then you can simply use s (i) to get all the variables associated with the i_th patient.

+1
source

This is clearly a bad design, but you can use the evalin function. Something like the following:

 cmd = sprintf('result_%s = %f', suffix, result); evalin('caller', cmd); 

Then you call your function myfunc without assigning its output.

Again, this is not a good idea, as most users do not expect this behavior. Functions are expected to return results, allowing the caller to assign the result to any variable that he chooses.

Good for small hacks, not long code.

+1
source

In addition to your comment, here is an example of using eval for the dynamic name of a workspace variable:

 >> string = 'patient1'; >> eval(strcat(string, '_finalresult = 200')) patient1_finalresult = 200 
0
source

All Articles