フィルターのクリア

Accessing local variables in a function.

23 ビュー (過去 30 日間)
Nupur
Nupur 2023 年 6 月 29 日
コメント済み: Steven Lord 2023 年 6 月 29 日
How can I acess the variable outside the function and thus store and show it in workspace?
function drawHexagon(sideLength, centerX, centerY)
% Calculate the coordinates of the hexagon vertices
angles = linspace(0, 2*pi, 7); % Angles for hexagon vertices
x = sideLength * sin(angles) + centerX; % x-coordinates of vertices
y = sideLength * cos(angles) + centerY; % y-coordinates of vertices
Nodes_unit_hex = [x',y'];
% Plot the hexagon
scatter(x, y );
axis equal;
grid on;
% Label the center point
text(centerX, centerY, 'C1', 'HorizontalAlignment', 'center');
end

採用された回答

Star Strider
Star Strider 2023 年 6 月 29 日
One option would be to return it as an output.
I am not certain which one you want to return, however assuming that it is ‘Nodes_unit_hex’ the function declaration would be:
function Nodes_unit_hex = drawHexagon(sideLength, centerX, centerY)
Note that whenever you call the function, it would be necessary to put a semicolon (;) at the end, to suppress printing the output even if you do not want to return it.
.
  3 件のコメント
Star Strider
Star Strider 2023 年 6 月 29 日
As always, my pleasure!
Steven Lord
Steven Lord 2023 年 6 月 29 日
Since I've seen people make this mistake before, defining the function to have an output argument is only one part of the solution. When you call the function you need to call it with an output argument as well. MATLAB doesn't magically "poof" a variable with the same name as the output argument into the workspace from which the function was called.
Also keep in mind that the name to which you assign the output(s) of the function don't have to match the names of the output arguments in the definition, as is the case in the example below. The function declares that it returns as its first output the variable named y in its workspace. The function call assigns that data to the variable named thisIsMyOutput in its caller's workspace.
thisIsMyOutput = sample1989863(1:10)
thisIsMyOutput = 1×10
1 4 9 16 25 36 49 64 81 100
function y = sample1989863(x)
y = x.^2;
end

サインインしてコメントする。

その他の回答 (1 件)

Torsten
Torsten 2023 年 6 月 29 日
移動済み: Torsten 2023 年 6 月 29 日
By defining them as output variables
function [x,y] = drawHexagon(sideLength, centerX, centerY)
and calling the function as
[x,y] = drawHexagon(sideLength, centerX, centerY)
?
  1 件のコメント
Nupur
Nupur 2023 年 6 月 29 日
sure,
Thanks a lot

サインインしてコメントする。

製品

Community Treasure Hunt

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

Start Hunting!

Translated by