How do I load a .mat file into a function when the file is named as a number string which is represented by a variable in the workspace from a previous process?

2 ビュー (過去 30 日間)
I have a script which analyses a photograph and saves the data into a .mat file. Each photograph in the folder is named a certain number, and the script prompts the user to input the reference number associated with their photograph of choice. This is then stored in a variable 'ref' as a string: e.g ref = '850'.
The script then proceeds to save the data in this case as 850.mat.
I then want to use this in a function, so to load the correct .mat file, I have been trying to load it in the following way:
load ref.mat - In this way, the previously stored ref variable which is present in the workspace as '850' would essentially load 850.mat, corresponding to the mat file I created previously.
Unfortunately this doesn't work and nothing I have tried (spent 3 hours searching for a solution) seems to work. The code is shown below:
*ref = num2str(input('Please enter reference number: '));*
After some calculations and manipulation...
*save(ref, 'timedata', 'tempdata');*
saving what in the previous example was 850.mat
If i now want to select that file to load into a function, what would I type so it always calls upon the file corresponding to the ref variable?
Thanks for your help in advance, and I hope I explained the question well enough!
Nik

採用された回答

Stephen23
Stephen23 2017 年 4 月 13 日
S = load([ref,'.mat'])
  1 件のコメント
Nikolaos Imellos
Nikolaos Imellos 2017 年 4 月 13 日
This (with all your help from before) works perfectly!
Thank you so much for your help and sorry for the initial confusion on my part!

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

その他の回答 (1 件)

Adam
Adam 2017 年 4 月 13 日
load( fullfile( ref, '.mat' );
or some variation of that if you want to load specific variables or assign the output to a struct rather than just spew them straight into the workspace, overwriting any of the same name that already exist.
  8 件のコメント
Stephen23
Stephen23 2017 年 4 月 13 日
編集済み: Stephen23 2017 年 4 月 13 日
Adams answer is incorrect, fullfile will creates this:
'850\.mat'
which shows that fullfile is inserting a file separator between filename and extension. See my answer for the correct code.
Adam
Adam 2017 年 4 月 13 日
Yes, that is true, it was a hasty untested answer off the top of my head based on usual constructs for these kind of situations!

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

カテゴリ

Help Center および File ExchangeVariables についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by