Passing array as input to a function
조회 수: 5 (최근 30일)
이전 댓글 표시
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
Stephen23
2023년 8월 23일
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
2023년 8월 23일
I did consider using arrayfun, but it seems my bias against using it has grown quite a bit.
답변 (1개)
Dyuman Joshi
2023년 8월 23일
편집: Dyuman Joshi
2023년 8월 23일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!