Passing array as input to a function
10 ビュー (過去 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!