Why do functions mask variables after using load inside a function?

Save this sample function as test_func.m :

 function test_func load test.mat whos alpha 

and run this sample script:

 alpha = 3; save test.mat test_func 

Here is the result I get:

  Name Size Bytes Class Attributes alpha 1x1 8 double ??? Error using ==> alpha at 40 Not enough input arguments. Error in ==> test_func at 4 alpha 

The output of whos indicates that the variable is being loaded into the local workspace of the function. I can even put a breakpoint on line 4 of test_func and type alpha and get the correct result, but as soon as I take a step forward with the debugger, it will work again: the alpha function masks the local variable, and I don’t understand why.

Replacing the contents of test_func with

 p = load('test.mat'); p.alpha 

works great, but that's not what I'm trying to do. I would like to load the variables directly into the local function workspace.

This seems like an error to me (I am using Matlab R2011a), but if it is a function, can you explain it and help me find a workaround?

+4
source share
1 answer

Hehe, you may be right that this is a mistake. It looks really weird because the following works

 function test_func load('test.mat','alpha'); whos alpha 

Another thing that helps is to initialize the variable before calling to load

 function test_func alpha = 0; load('test.mat'); whos alpha 
+3
source

Source: https://habr.com/ru/post/1437009/


All Articles