My code like this but what should I do to change the code so that it automatically calcultes the matrix for p=4 without using for loops. I want to convert this function into a recursive function.
function M=FakLoop3
p=3;
v=0;
indis=zeros(1,p);
M=zeros(2^p,p)
for i=0:1
indis(1)=i;
for j=0:1
indis(2)=j;
for k=0:1
indis(3)=k;
v=v+1;
M(v,:)=indis;
end
end
end
end

댓글 수: 4

Torsten
Torsten 2019년 4월 3일
https://www.researchgate.net/post/How_can_I_generate_all_combinations_of_0_1_in_MATLAB
A recursive function will not be efficient in Matlab. Therefore I assume that this is a homework. Then posting a working solution would not be useful. So please post, what you have tried so far and ask a specific question.
Efficient would be an inlined dec2bin:
M = rem(floor((0:2^p-1).' .* 2 .^ (1-p:0)), 2)
Maaz ul mosaid
Maaz ul mosaid 2019년 4월 3일
This is not a homework. I am trying to replace the for loops so that it can vary with p, I think recursive is the solution to this problem. Please post the solution if you can.
Jan
Jan 2019년 4월 3일
편집: Jan 2019년 4월 3일
I've posted an efficient solution already. I repeat it in an answer. Of course you can solve this by recursion, but the shown method is much more efficient.

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

답변 (1개)

Jan
Jan 2019년 4월 3일
편집: Jan 2019년 4월 3일

3 개 추천

Inlined dec2bin(0:2^p-1):
M = rem(floor((0:2^p-1).' .* 2 .^ (1-p:0)), 2)
Another solution:
M = zeros(2^p, p, 'uint8');
n1 = 1;
n2 = 2^(p-1);
v = uint8([0;1]);
for k = 1:p
M(:, k) = repmat(repelem(v, n2, 1), n1, 1);
n1 = n1 * 2;
n2 = n2 / 2;
end
Or:
M = zeros(2^p, p, 'uint8');
v = uint8(0:2^p-1).';
for k = p:-1:1
M(:, k) = bitget(v, 1);
v = bitshift(v, -1);
end
With doubles instead:
M = zeros(2^p, p, 'uint8');
v = (0:2^p-1).';
for k = p:-1:1
M(:, k) = rem(v, 2);
v = floor(v / 2);
end

카테고리

도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

릴리스

R2016a

태그

질문:

2019년 4월 3일

편집:

Jan
2019년 4월 3일

Community Treasure Hunt

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

Start Hunting!

Translated by