フィルターのクリア

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 Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by