フィルターのクリア

Reading variables from workspace

48 ビュー (過去 30 日間)
amberly hadden
amberly hadden 2015 年 9 月 9 日
回答済み: Sulaymon Eshkabilov 2019 年 2 月 4 日
Hi- I was wondering if there is a way to read all variables from workspace ? I want to make a .mat file so if I run my simulation its spitting 20 variables in work space. I want to write these in a mat file e.g.
data = [a b c d f r g];
save data.mat data
Is there a way in which program read all variables from workspace?
Thank you
  1 件のコメント
Star Strider
Star Strider 2015 年 9 月 9 日
The code you posted should work, and will save your ‘data’ matrix to your ‘data.mat’ file.
What is not working as you want it to?

サインインしてコメントする。

採用された回答

Hamoon
Hamoon 2015 年 9 月 9 日
If you want to save all the variables from workspace to a file named data.mat you just need this:
save('data')
  3 件のコメント
Hamoon
Hamoon 2015 年 9 月 9 日
Wow, I got wrong. if you want to have data=[a b c ...] use this:
myvars = who';
str = strjoin(myvars,' ');
eval(['data=[',str,']']);
if all of your variables are arrays with dimention of n*1 you need to make data=[a;b;c;d...] that means they have semicolon between them, so use the following as the second line of the code:
str = strjoin(myvars,';');
Hamoon
Hamoon 2015 年 9 月 11 日
You chose my answer as accepted answer, thank you, but be aware, Walter Robinson's answer (the next answer) is the best way to reach your goal, my answer is just for your current work, and it's not an efficient way to reach your goal generally, but Walter's is good and efficient for this matter. If you can deal with programming part of that concept, please try that one.

サインインしてコメントする。

その他の回答 (2 件)

Walter Roberson
Walter Roberson 2015 年 9 月 9 日
Do not create those variables dynamically in the workspace. Create fields of a structure. You can then save to a .mat file as individual variables using the save -struct option.
If you have a .mat file with a number of variables and you want to work on each of them, then use
datastruct = load('YourFile.mat');
Now each of the variables in the .mat file will appear as fields in datastruct. You can find out what is there using fieldnames(datastruct) . If you want to apply the same operation to each variable you can do that using structfun()
  1 件のコメント
amberly hadden
amberly hadden 2015 年 9 月 10 日
Thank you Walter I always appreciate your help

サインインしてコメントする。


Sulaymon Eshkabilov
Sulaymon Eshkabilov 2019 年 2 月 4 日
Here is an alternative (simpler) solution to the problem:
% save all variables in the workspace:
save('MYdata.mat');
% Store the variable names from mydat.mat in a cell: MYvars
MYvars = who('-file', 'MYdata.mat');
for k = 1:length(MYvars)
disp(MYvars{k})
end

カテゴリ

Help Center および File ExchangeModeling and Prediction についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by