How do I make an output variable from a sub-routine function a variable in the main function/script? I have a function that reads data from a .txt file (data for output variable) and I want that data in my main file. Is there something I'm missing?

조회 수: 5 (최근 30일)
function [ Output ] = readData(inputvariable= opened .txt file)
data = fscanf( opened.txt, '%f', 4);
return
end

답변 (1개)

Star Strider
Star Strider 2015년 7월 26일
Without knowing more than you stated in your Question, I would code it (passing the argument) as :
function [ data ] = readData(inputvariable)
data = fscanf( inputvariable, '%f', 4);
return
end
Your ‘inputvariable’ argument is the file identification (’fid’) number of the file you already opened.
I would pass the filename and let the function open, read, and close the file, but you may have your own reasons for passing the file id to your function instead.
  댓글 수: 2
Michael Polewski
Michael Polewski 2015년 7월 26일
yes, I need to create several functions to read from one file, I'm just trying to get the data I read into the main file. I'm trying to find out how to get the local variable from the function into the main script without setting the data as a global variable. This is my first time using matlab, so I apologize if there is a simple function that allows me to do this.
Star Strider
Star Strider 2015년 7월 26일
You don’t need to set ‘data’ as a global variable. Just create it as an output (returned value) from your function, do not overwrite it in any subsequent assignments, and use it wherever you want.

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by