Dynamic variables matlab - matlab

How can I access to dynamic variables in Matlab? I search for similar question but I didn't find.
Example (simplified):
for i=1:1
aux3=(i-1)*50;
delay_64_264(1,i) = mean(delay_64_264_', num2str(aux3), ' (:,3)*100;
end
What I want to do is mean of column 3 from variable delay_64_264_0.
Anyone can help me?
Thank you very much

You can use eval().
But I recommend not doing this at all. Use a multidimensional array, rather than lots of variables with slightly different names.

To follow on from Oli's suggestions, see this piece of the MATLAB FAQ:
http://matlab.wikia.com/wiki/FAQ#How_can_I_create_variables_A1.2C_A2.2C....2CA10_in_a_loop.3F
which shows how to use structures and cell arrays as an alternative to eval.

Related

derivate of a two variable function on one point ti-nspire

The image shows my problem (link)
I want to use that to do a Jacobian for a Multivariable method of aproximation. So There is a way to use that easily? or I have to put manually the partial derivatives like new functions?
I'm sorry for my english.
Firstly, you dont have to use images here, you can easily insert code pieces. As for your problem, i didnt understand it. Im sure you already know that you can define a Jacobian matrix function of 2 variables:
j2_fun(f1,f2):=[[derivative(f1,x),derivative(f1,y)][derivative(f2,x),derivative(f2,y)]]
... and call it later with specific arguments, and evaluate for some x,y:
g1:=x^2+y^2
g2:=x^2-y^2
d2:=j2_fun(g1,g2)
d2|x=3 and y=1
So staring from here, please define more clearly what would you like to do with this.

Get variable content from his name Matlab [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I want to get the content of a variable from its name as a string:
%suppose that I have structures variables in the workspace:
struct_1=struct('field1' ,"str",'field2',0:5)
struct_2=struct('field1' ,"str",'field2',0:10)
struct_3=struct('field1' ,"str",'field2',0:20)
%and I have an other variable like:
a=5
var2='hello'
%and I want to concatenate all these structures in the same structure
%So i wan to get their name.
%I don't know if there is an other way to get just the structure variables
structures=who(str*)
array=[]
for i=1:length(structures)
array=[array; structures(i). field2]; % here I get an error because the content of structures are string representing the variable name
end
%create the new struct
str='newstr_value'
struct_4=struct('field1',str, 'field2',array)
How to fix this error and is there any way to do this better ?
While I would still highly recommend going back to the point of origin of these dynamically named structures (shame 🔔🔔🔔 on the toolbox creator if this is actually the output...) and fixing this problem there, there is an approach that does not require the use of eval.
Similar to my approach for a tangentially related question, you can save the desired structures to a temporary *.mat file and take advantage of load's optional structure output to consolidate the data structures for access in a more robust programmatic matter.
For example:
struct_1=struct('field1' ,"str",'field2',0:5);
struct_2=struct('field1' ,"str",'field2',0:10);
struct_3=struct('field1' ,"str",'field2',0:20);
save('tmp.mat', '-regexp', '^struct_');
clear
oldworkspace = load('tmp.mat');
varnames = fieldnames(oldworkspace);
nvars = numel(varnames);
% Get original structure fields
% The subsequent steps assume that all input structs have the same fields
fields = fieldnames(oldworkspace.(varnames{1}));
nfields = numel(fields);
% Initialize output struct
for ii = 1:nfields
newstruct.(fields{ii}) = [];
end
newstruct(nvars) = newstruct;
for ii = 1:nvars
for jj = 1:nfields
newstruct(ii).(fields{jj}) = oldworkspace.(varnames{ii}).(fields{jj});
end
end
Gives us:
Yay.
Not sure if your situation absolutely requires dynamic calls of variables by their string names. eval can solve your problem. However, eval is slow. At times, it is unreliable. You can easily have conflicting code as you build various components of your project. And in my experience, there have always been alternatives to eval. In your case, Adriaan outlined an example in his comment.
Since you are only trying to interface with a third-party toolbox, if the number of variables you read is reasonable, you can do the followings with eval.
array=struct;
for i=1:length(structures)
eval(['array(',num2str(i),').field2=',structures{i},';'])
end
If you know all the structs are named struct_#, you can also do
array=struct;
num=3; % the number of outputs from your toolbox
for i=1:num
eval(['array(',num2str(i),').field2=struct_',num2str(i),'.field2;'])
end
Note that your field2 values are all arrays. You can't just create an array and expect each "cell" to carry another array value. Arrays, or rather matrices, in Matlab are a special data type. They only take numerical values. (Matrices are highly optimized in Matlab in various ways. That is why we use Matlab.)
Also note that when you set equality of fields of structs, the equality is by reference. There is no deep copy of the data. Modifying one will modify another. (Just beware of this but don't necessarily rely on it. Deciding when to deep copy things is one of the things we let Matlab handle.)
As well, be careful with the result from who. You need to be absolutely clear with what is in the local scope. Above is assuming your result from calling structures=who(str*) is correct for your application.

Change a name and assign matrix in matlab

I wish to change the name of col_1 to col_2, col_3....col_N for each value of 'j'. Could anyone suggest on how to handle this.? The reason why I wish to do this way is that size of col_i changes for different j. Any valuable suggestions and corrections are highly appreciated.
for j=1:N
for i=1:dum+1
col_1(i,1)=x;
col_1(i,2)=y;
end
end
you can use eval like the following:
for j=1:N
for i=1:dum+1
eval(strcat(strcat('col_',num2str(j)),'(i,1)=x'));
eval(strcat(strcat('col_',num2str(j)),'(i,2)=y'));
end
end
#KGV dynamic naming convention is not suggested in MATLAB. You have the indices already, you can call them easily. Don't try to rename/ use dynamic naming convention. You may read the below link for further information.
https://in.mathworks.com/matlabcentral/answers/105936-how-to-make-dynamic-variable-names-a1-a2-an-with-for-loop-using-eval-num2str

What is the difference between comma separated or not MATLAB function return?

I forgot commas between some returns of a function in MATLAB and it did not complain.
function [returnA, returnB]=foo(paramA)
returnA=ones(1,10).*paramA;
returnB=magic(4);
end
function[]=voo()
%typing the return as this
[A,B]=foo(5);
%gives the same result as
[A B]=foo(5);
end
My question is: is it exactly the same behavior? I was not able to find it in documentation
Yes, it is the same behavior, as seen with the code you provide in your question.
As #LuisMendo points out in the comments, if you look at the MATLAB's lint (aka Code Analyzer) message in the editor you'll see:
Best practice is to separate output variables with commas
Which implies that both syntaxes are valid. As to why this is the case I'm not sure, and I can't really find anything specific which tends to point towards "just because." As #rayryeng points out in the comments, it could also have to do with aligning syntax with MATLAB's comma-separated lists.

How can I create multiple inputs for a matlab function block?

I want to restrict the variable that I use as input for a matlab function block, it must be only able to increase.
To achieve that i have tried to compare the variable and the previous sample of it in a matlab function, but i don't know how to create two inputs. To solve that i've tried to use a mux, but then i get an error. And google doesn't give me an explanation how to use a mux signal as input for a matlab function.
So that leaves me here with this low-level question.
Thanks in advance for your help and time. Cheers.
To use multiple variables in a function, you need to modify your function declaration at the first line of your function. The reference syntax is:
function [y1,...,yN] = myfun(x1,...,xM)
where x1 through xM are inputs. Your declaration with two inputs might look something like:
function [returnValue] = hasIncreased(previousSample, variable)
See the Matlab Function Documentation for more information.