using function in matlab
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
hi,i want to write a function who get radius and number of circles that should be in the primary circle.
this is what i wrote till now,but still it not call to the function unfortunately.
function [ ] = drawcircle( r,n )
hold on;
for i:1:n
theta=linspace(2*pi/n,2*pi,n);
x=r*cos(theta);
y=r*sin(theta);
plot(y,x)
hold off;
main -
count=3;
r=5;
theta=linspace(0,2*pi);
drawcircle(r,count);
plot(y,x)
0 commentaires
Réponses (1)
Steven Lord
le 19 Sep 2017
In the future, please format your code using the {}Code button. You can select all the code and press that button and it will be automatically formatted.
You or someone else has tagged this homework, but you showed what you'd done. Thank you for showing your work.
You expected to be able to use the x and y variables that were created inside drawcircle outside of that function, but were surprised when that threw an error. Correct? The issue is that each function operates in its own workspace that is its "private play area". Functions generally [*] don't have access to variables and data outside their own workspaces.
If you want a function to work on data from outside, you should pass it into the function as an input argument. If you want to be able to work outside on data created within the function, you should return it from the function as an output argument.
In this case, you're passing data into your drawcircle function. The data stored in the r variable in the "main" workspace from which drawcircle was called is accessible inside drawcircle, and in that function its name is r. Similarly the data stored in count outside is accessible inside, but inside it is known as n. But you're not passing data out of drawcircle. To do that, see the "Output arguments" row of the table in the Syntax for Function Definition section on this documentation page.
Once you've defined drawcircle to return x and y as output arguments, you only need to call drawcircle with two outputs in order for that data to be accessible outside the function.
[*] Yes, I know there are other techniques by which functions can share data other than input and output arguments. This seems like homework for a course where the students are being introduced to MATLAB so I want to keep things simple.
11 commentaires
Walter Roberson
le 9 Oct 2017
I am not sure what you mean about "the gaps between each circle is the same in the x-y plane" ? Could you give a sample diagram?
Voir également
Catégories
En savoir plus sur Convert Image Type dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!