필터 지우기
필터 지우기

any suggestion to store answer after for loop into a matrix to use later?

조회 수: 1 (최근 30일)
Quoc Khang Doan
Quoc Khang Doan 2021년 3월 22일
편집: Jan 2021년 3월 27일
this is what i have so far, it only store the answer of the last entry of x (N) into matrix b, which was supposed to have all the binary entries for each entry of x (from 0 upto N). Any improvement I can make to achieve that?
function [x] = mybinplot(N)
x = 0:N;
for d = 0:N
if d == 0
b = 0;
else
p = 0;
while 2^p <= d
p = p + 1;
end
b = zeros(p,length(x));
power = p-1;
for ii = 1:length(b)
if d >= 2^power
b(ii) = 1;
d = d - 2^power;
end
power = power - 1;
end
end
end
z = fliplr(b);
disp(z)

채택된 답변

Jan
Jan 2021년 3월 22일
편집: Jan 2021년 3월 27일
x = 0:N;
b = zeros(ceil(log2(N)), length(x)); % Move this BEFORE the loop to avoid overwriting
for d = 1:N
p = 0;
while 2^p <= d
p = p + 1;
end
power = p-1;
for ii = 1:p
if d >= 2^power
b(ii, d + 1) = 1;
d = d - 2^power;
end
power = power - 1;
end
end
But the result looks strange:
b =
0 1 1 1 1 1
0 1 0 0 0 0
0 1 0 0 0 0
You forgot to mention, what your code should achieve.
By the way, v=ceil(log2(N)) is a vector. Then zeros(v, length(x)) is working, but a confusing exception. Better use the scalar ceil(log2(max(N))) .
[EDITED] Of course this works as good or bad as the original code also. I could not post a working version directly, because you did not explain, what you want to get. The actual question "store answer after for loop into a matrix to use later?" did not clarify this.
After reading your comment:
x = 0:5;
Len = ceil(log2(max(x)));
z = rem(floor(pow2(1-Len:0).' * x), 2);
Or with a loop:
x = 0:5;
Len = ceil(log2(max(x)));
b = zeros(Len, numel(x));
for k = Len:-1:1 % From bottom to top:
b(k, :) = rem(x, 2);
x = floor(x / 2);
end
  댓글 수: 1
Quoc Khang Doan
Quoc Khang Doan 2021년 3월 26일
편집: Quoc Khang Doan 2021년 3월 26일
What i want to achieve is convert every element in x, for example:
>> x = 0:5;
x = 0 1 2 3 4 5
into binary and store it into a matrix z like so:
>> mybinplot(5)
z =
0 0 0 0 1 1
0 0 1 1 0 0
0 1 0 1 0 1
thank you in advance

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

추가 답변 (0개)

카테고리

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