5

I want to create a function function ExtremePoints = AnalyseData( ScanData ).

I want to be able to run the function without passing the argument ScanData, and in this situation I want to use a variable with the same name from Matlab Workspace.

Is this possible, to use inside the body of the function the variable ScanData which appear in workspace?

Or should I first save the content of the variable ScanData from workspace into a .mat file and then load that file in the body of the function?

3
  • 3
    As @Edric already mentions: it is (strongly) discouraged to do so, as you will not be able to properly reuse the function somewhere else without much pain (missing variables, something completely different stored in ScanData, less clear code, mlint will not warn you for your mistakes inside eval or evalin, ...). So do yourself a favor and refrain from using these when you don't have to! Commented Jul 27, 2011 at 12:29
  • The thing is that the mentioned function is used more as a test script and instead of launching the call from Command Window, I want to call the function directly from the editor and that's the reason for asking this question. Thanks for the advice though! :) Commented Jul 27, 2011 at 15:46
  • 1
    there are some different things you can do. First of all you could make it a script instead of a function (just leave out the function ...). All variables will then be part of your base workspace. So this might become cluttered and you might need to play around with things like clear variables; close all; clc; for convenience. Or you could use the run configurations feature. However, these are cumbersome to keep track of in version control or on different computers. So both have pros and cons. Commented Jul 27, 2011 at 21:43

1 Answer 1

11

It is possible, perhaps not entirely recommended. Here's how:

function ExtremePoints = AnalyseData( ScanData )
if nargin == 0
    ScanData = evalin( 'base', 'ScanData' );
end
% do stuff

This pulls the value of ScanData from the base workspace if no input arguments are supplied (nargin == 0).

Use of eval and evalin is generally discouraged as it makes your code harder to understand and re-use.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.