Loading data in a function and passing it

조회 수: 6 (최근 30일)
Richard Prince
Richard Prince 2017년 2월 24일
댓글: Richard Prince 2017년 2월 24일
Hello all. I'm trying to write a function that checks for the existence of a series of variables. If they exist, I want the function to do nothing. If they don't exist, I want the function to load them into the workspace and pass them to the main workspace. When I run my code however, it loads the first file and assigns it to variable ans. Any help is appreciated.
function [cntREF, sREFn, w] = LoadClassData
%%%%Loads the preset data created by the training algorithm
if exist('B', 'var') == 1
return;
else
load('B.mat');
end
if exist('cntREF', 'var') == 1
return;
else
load('cntREF.mat');
end
if exist('sREFn', 'var') == 1
return;
else
load('sREFn.mat');
end
if exist('w', 'var') == 1
return;
else
load('w.mat');
end
end
  댓글 수: 1
Richard Prince
Richard Prince 2017년 2월 24일
Also I should mention above that when I run the function with the variables already in place it is executing the else statements anyway. Is this some kind of local workspace problem?

댓글을 달려면 로그인하십시오.

채택된 답변

Jan
Jan 2017년 2월 24일
Each function has its own WorkSpace. Because your function does not have any input, there are no variables defined at the beginning:
function [cntREF, sREFn, w] = LoadClassData
if exist('B', 'var') == 1
% Cannot happen under any circumstances
end
Now you can load the MAT file to the variable B, but it is not provided as output and therefore it does not appear in the caller. The is the meaning of functions: hide everything, what happens internally except for inputs and outputs.
  댓글 수: 1
Richard Prince
Richard Prince 2017년 2월 24일
Thanks that clears it up quite a bit. Is there a way to effectively implement what I want in a function, or should I just move all the if-statements into the body of the main code?

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

kowshik Thopalli
kowshik Thopalli 2017년 2월 24일
In the else condition- write b=load('b.mat'), w=load('w.mat') etc. Does this solve your problem?
  댓글 수: 2
Richard Prince
Richard Prince 2017년 2월 24일
No this changes the datatype of the variable being loaded. Also I should mention above that when I run the function with the variables already in place it is executing the else statements anyway. Is this some kind of local workspace problem?
kowshik Thopalli
kowshik Thopalli 2017년 2월 24일
Yes You are right. It becomes a structure.You have to then access using b.b; Yes. Functions have their own work space which is different from base workspace . Return the loaded matfiles to the script that calls this function.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Workspace Variables and MAT Files에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by