Filter löschen
Filter löschen

How to store a vector that is read from the workspace to the workspace again

6 Ansichten (letzte 30 Tage)
eg a vector name: vals
Maybe I can use this function: evalin('base','vals(1) = 8');%%the first element is set to 8;it's OK.
but now I have no idea about the value or index,I have to write as follows: n=1;va=8;evalin('base','vals(n)=va');but there are some errors so can you fix it?
  1 Kommentar
Stephen23
Stephen23 am 21 Jul. 2015
Bearbeitet: Stephen23 am 21 Jul. 2015
If you pass the values as arguments then you will avoid all of those errors:
Really using evalin is a terrible way to pass values, although beginners seem to love using it and are then surprised at all the errors and buggy code that they end up with. Below is an explanation of why using eval is a poor programming practice, most of it also applies to evalin too (and your indexing problems):
Avoid creating dynamically named variables in MATLAB. This is poor practice as has been explained many times on this forum, and is not recommended by MATLAB themselves:
When you are a beginner it seems like a cunning and fast way to store information, but actually it is really bad practice to name your variables dynamically. MATLAB is also not intended for this kind of variable naming: if you continue to include data in the variable names then you will find yourself fighting many more of these battles against MATLAB.
However when you use more appropriate storage for your data (and meta-data) then you will suddenly find lots of MATLAB functions that do many useful operations for you, quickly and easily.
In your case a much more robust solution would be to use:
There are many functions that support working on structures and cell arrays, and can access these data easily, and they can also be used in vectorized code (which is something you need to learn about).
Placing your data in a structure or cell array also makes it much easier to pass to functions: can you imagine the fight you would have trying to pass hundreds of dynamically named variables to a function?
If you have a newer version of matlab you can also use a table , which stores the data together in one array but also allows key-name access to the columns. This might be a good alternative for your data.
In case you are interested, here are some pages explaining why dynamically assigning variable names is a really bad idea in MATLAB:
Here is a discussion of why it is a bad idea to include meta-data (such as an index) in a variable name:
And for some other languages advising "DO NOT create dynamic variable names":

Melden Sie sich an, um zu kommentieren.

Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by