Using output variables from one function as inputs for another

조회 수: 4 (최근 30일)
Bryce Klenk
Bryce Klenk 2021년 4월 23일
답변: Jan 2021년 4월 23일
I'm trying to use the 'days' and 'daily_deaths' outputs from my 'process_data' function as inputs for my 'global_deaths' function, but I have no idea how to set it up. I've searched this forum for people asking similar questions, but the answers they recieved only further confused me. Can anybody help me?
function global_deaths(daily_deaths, days, avg_days)
process_data();
plot(days,daily_deaths);
grid on
txt = sprintf('Daily deaths from day %d to day %d of the pandemic',min(days(:)),max(days(:)));
title(txt)
ylabel('Deaths');
xlabel('Day')
axis([min(days(:)) max(days(:)) min(daily_deaths(:)) max(daily_deaths(:))]);
hold on
avg_days = movmean(daily_deaths,[6 0])
hold off
end

답변 (2개)

DGM
DGM 2021년 4월 23일
Not knowing what processdata() does or whether it has any outputs at all, I can't say.
When you define a function, define its input arguments and output arguments. If you don't have any output arguments, then you don't have anything to pass to another function (unless you're abusing globals or using nested functions with shared variables).
This is a basic example of two functions:
% take the output from one function
intermediateresult = addnumbers(3,4)
% and pass it to another
finalresult = multiplynumbers(intermediateresult,3)
% function is defined with input arguments and output arguments
function out = addnumbers(A,B)
out = A+B;
end
% again, function has input and output arguments
function out = multiplynumbers(A,B)
out = A.*B;
end
The result is (3+4)*3=21
The two functions are independent scopes. A,B in the first function are not the same conceptual entities as the A and B in the second function. They exist only in their respective scope.

Jan
Jan 2021년 4월 23일
If the variables "days" and "daily_deaths" are output of the function process_data(), you have to catch the outputs:
[days, daily_deaths] = process_data();
plot(days,daily_deaths);

카테고리

Help CenterFile Exchange에서 Introduction to Installation and Licensing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by