How to use data in a script from a function in another.

I'm new to matlab and am trying to learn functions. For example, I have this function saved in a folder:
%example function
function Bricks = UseBrickData
Bricks.Red.Height = 10;
Bricks.Yellow.Height = 20;
end
I create another general script in the same folder, this is the script I'm using to do my calculations. How do I use the data from the Bricks function in this new general script? How do I specifically use the Red Height and the Yellow Height in this new general script?

댓글 수: 1

S = UseBrickData();
S.Red.Height
ans = 10
S.Yellow.Height
ans = 20
%example function
function Bricks = UseBrickData
Bricks.Red.Height = 10;
Bricks.Yellow.Height = 20;
end

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

답변 (1개)

Les Beckham
Les Beckham 2022년 10월 11일
편집: Les Beckham 2022년 10월 11일
% Example script
NewBricks = UseBrickData(); % Call the function and assign the return value to the variable NewBricks
disp(NewBricks.Red.Height)
10
disp(NewBricks.Yellow.Height)
20
% example function - if you want to be able to call it from anywhere, save
% it in a file called UseBrickData.m instead of inside your script
function Bricks = UseBrickData()
Bricks.Red.Height = 10;
Bricks.Yellow.Height = 20;
end
Also (FWIW), since this function doesn't use the data, it creates it, you might want to call it CreateBrickData() or DefineBrickData().

카테고리

도움말 센터 및 File Exchange에서 Programming에 대해 자세히 알아보기

태그

질문:

2022년 10월 11일

댓글:

2022년 10월 11일

Community Treasure Hunt

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

Start Hunting!

Translated by