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)
0 个评论
采纳的回答
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Error Detection and Correction 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!