Making a filename into a variable

I have a script where I load in some data with a function. "function MyScript('file1.dat','file2.dat','file3.dat')"
I do some calculations so I have the two numbers I want in a vector X. Now I want Matlab to write:
"Calculated file2 = X(1)"
"Calculated file3 = X(2)"
with the filename as text, and showing the value of X.

3 commentaires

The question is not clear: "function MyScript(file1.dat,file2.dat,file3.dat)" is not valid Matlab-syntax. Do you mean
function MyScript(file1, file2, file3)
which is called as:
MyScript('file1.dat', 'file2.dat', 'file3.dat')
? Where should "Calculated file2 = X(1)" appear, when you want to "write" it? and which filename should appear as "text"?
Please edit your question and do not post the important details as a comment. Thanks.
Alexander Kjærsgaard
Alexander Kjærsgaard le 15 Nov 2016
Modifié(e) : Alexander Kjærsgaard le 15 Nov 2016
Hi, the function part was a typo on my part (fixed). So I want a variable called "Calculated file2", and file2 is of course the name of my file2 and I want it to work, so when I in my script write Calculated file2 I want it to show the value of X(1).
So when I run the script, it will show up in my command window like:
Calculated file2 =
X(1)
With the filename of file2, which is all text, and the value of X(1)
You can't have spaces in variable names and it is not advisable to name variables sequentially after files or other numbered inputs.
An array works far better.
doc sprintf
should be used to print things out to the screen too. Variable names are internal to a function, they should certainly have names that make sense to the programmer, but they shouldn't ever require to be exposed to an external user of the function. Using sprintf you can put together text on the screen saying whatever you want, without being constrained trying to name variables to achieve it.

Connectez-vous pour commenter.

Réponses (1)

Image Analyst
Image Analyst le 15 Nov 2016
You cannot have the function declaration line be this:
function MyScript(file1.dat,file2.dat,file3.dat)
The .dats are not allowed. And MyScript is a bad name for a function since it's a function and not a script. You can do this
function MyFunction(file1, file2, file3)
Inside that function you can compute X and print it out to the command window like this:
fprintf('Calculated %s = %f\n', file2, X(1));
fprintf('Calculated %s = %f\n', file3, X(2));

Community Treasure Hunt

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

Start Hunting!

Translated by