필터 지우기
필터 지우기

combination function using ndgrid

조회 수: 2 (최근 30일)
Nik Sam
Nik Sam 2016년 5월 18일
댓글: Nik Sam 2016년 5월 19일
Hello,
I want to build a function which use ndgrid.
My function is
function [ varargout ] = comb( varargin )
[varargout]=ndgrid(varargin)
varargout=varargout(:);
disp([varargout])
end
My varargout are x1 x2 x3 and varargin are a,b,c where a=[1 2], b=[2 3] and c=[1 4]. Expected results are
1 2 1
2 2 1
1 3 1
2 3 1
1 2 4
2 2 4
1 3 4
2 3 4
but it seems like ndgrid doesn't work. What can i do? In command window works fine but as a function where I can put more varargins something is wrong.

채택된 답변

Guillaume
Guillaume 2016년 5월 18일
function varargout = comb(varargin)
varargout = cell(1, nargout);
[varargout{:}] = ndgrid(varargin{:}; %distribute to varargout
varargout = cellfun(@(m) reshape(m, [], 1), varargout, 'UniformOutput', false); %reshape into columns
end
  댓글 수: 10
Guillaume
Guillaume 2016년 5월 19일
[varargout{:}]
at the end of the function will do it. This will always display the output whether or not you terminate the call to comb with a semicolon, so I wouldn't recommend it.
There is no way to detect if a function has called with a semicolon or not, so you can't toggle that behaviour.
Nik Sam
Nik Sam 2016년 5월 19일
Really thanks for your time my friend..Now finally I have the desired result..
Thanks again...

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Walter Roberson
Walter Roberson 2016년 5월 18일
[varargout{:}] = ndgrid(varargin{:});
  댓글 수: 3
Walter Roberson
Walter Roberson 2016년 5월 18일
function [ varargout ] = comb( varargin )
[varargout{1:nargout}] = ndgrid(varargin{:});
end
Nik Sam
Nik Sam 2016년 5월 18일
This works my friend but if I run the following
>> a=[1,2];
>> b=[2,3];
>> c=[1,4];
>> [x1,x2,x3]=comb(a,b,c)
I get this
x1(:,:,1) =
1 1
2 2
x1(:,:,2) =
1 1
2 2
x2(:,:,1) =
2 3
2 3
x2(:,:,2) =
2 3
2 3
x3(:,:,1) =
1 1
1 1
x3(:,:,2) =
4 4
4 4
But i want as result:
1 2 1
2 2 1
1 3 1
2 3 1
1 2 4
2 2 4
1 3 4
2 3 4

댓글을 달려면 로그인하십시오.


Jos (10584)
Jos (10584) 2016년 5월 18일
Take a look the content of ALLCOMB, which does exactly what you're after btw...

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by