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

1 次查看(过去 30 天)
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 中查找有关 Error Detection and Correction 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by