Passing array as input to a function
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Hi, im trying to pass the following arrays into the self created function DrawRegularPolygon but Matlab is prompting me matrix dimension errors. Can someone help
n = [3,4] ;
D = [2,1] ;
a = [0,0] ;
[xseries, yseries] = DrawRegularPolygon ( n , D , a) ;
function [xseries, yseries] = DrawRegularPolygon ( nosides , Diameter , alpha )
ThetaSeries = ( (0 + alpha).*pi ) : ( 2*pi./nosides ) : ( (2 + alpha).*pi ) ;
xseries = (Diameter./2) .* cos(ThetaSeries) ;
yseries = (Diameter./2) .* sin(ThetaSeries) ;
end
2 comentarios
Stephen23
el 23 de Ag. de 2023
The outputs are different sizes. You could easily use ARRAYFUN:
n = [3,4] ;
D = [2,1] ;
a = [0,0] ;
[xseries, yseries] = arrayfun(@DrawRegularPolygon, n , D , a, 'uni',false)
function [xseries, yseries] = DrawRegularPolygon ( nosides , Diameter , alpha )
ThetaSeries = ( (0 + alpha).*pi ) : ( 2*pi./nosides ) : ( (2 + alpha).*pi );
xseries = (Diameter./2) .* cos(ThetaSeries);
yseries = (Diameter./2) .* sin(ThetaSeries);
end
Dyuman Joshi
el 23 de Ag. de 2023
I did consider using arrayfun, but it seems my bias against using it has grown quite a bit.
Respuestas (1)
Dyuman Joshi
el 23 de Ag. de 2023
Editada: Dyuman Joshi
el 23 de Ag. de 2023
If you perform colon operations with vectors to create regularly-spaced vectors, it will only take the 1st element of each vector in consideration.
From the documentation of colon, : - "If you specify nonscalar arrays, then MATLAB interprets j:i:k as j(1):i(1):k(1)."
%Example
[1 2]:[0.5 0.75]:[3 4]
You can use a for loop to make regularly-spaced vectors corresponding to each element of inputs, and since number of elements of the generated vector will vary, use a cell array to store them -
n = [3,4] ;
D = [2,1] ;
a = [0,0] ;
C = DrawRegularPolygon ( n , D , a)
function C = DrawRegularPolygon ( nosides , Diameter , alpha )
n = numel(nosides);
%2 row cell array - 1st row for xseries, 2nd row for yseries
C = cell(2,n);
%Assuming all the input variables have same number of elements
for k=1:numel(nosides)
ThetaSeries = ( (0 + alpha(k)).*pi ) : ( 2*pi./nosides(k) ) : ( (2 + alpha(k)).*pi );
xseries = (Diameter(k)./2) .* cos(ThetaSeries);
yseries = (Diameter(k)./2) .* sin(ThetaSeries);
C{1,k} = xseries;
C{2,k} = yseries;
end
end
P.S - You can use a check in the code as well to see if the inputs have similar dimensions or not.
0 comentarios
Ver también
Categorías
Más información sobre Resizing and Reshaping Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!