Clear Filters
Clear Filters

Store variables in strings and invoke them

1 view (last 30 days)
Giulio
Giulio on 15 Jun 2013
Hi!
I'm doing a bioinformatic analysis on miRNAs and I have a lots of code repetition in order to do the same operations to different datasets. I wonder if it would be possible to store the variables name into strings/cells and somehow execute scripts in a cycle that explores all the string/cell positions
For example
massCP=zeros(maxCP-2,1);
for i=maxCP:-1:1
massCP(i,1)=i;
A=sum(sum(nCP==i));
massCP(i,2)=A;
end
massCP=flipud(massCP);
patternCP=cell(max(massCP(:,2))+1,maxCP);
%%if true%%
for i=1:maxCP
patternCP{1,i}=horzcat('--',num2str(i),'--');
end
%%if true%%
for i=1:maxCP
[r,c]=find(nCP==i);
for j=1:length(r)
patternCP{j+1,i}=CGImageBack(r(j),c(j),n);
end
end
%%end%%
(I need to do this for different variables: CM, MM1, MP1, ...)
the ideal thing would be having those variables stored and called in a cycle.
Is it possible? or should I leave the code as it is (with 6 code repetition with just the variable that changes?)

Answers (2)

Walter Roberson
Walter Roberson on 15 Jun 2013

Iain
Iain on 15 Jun 2013
I would suggest that you use functions.
You can store a variable name in a string, and use it, but its slower, and more likely to go wrong.
eval([ ' current_variable = ' string_containing_variable_you_want_to_use ';'])
or
current_variable = eval(string_containing_variable_you_want_to_use);

Products

Community Treasure Hunt

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

Start Hunting!