Convert integer value to a vector
28 ビュー (過去 30 日間)
古いコメントを表示
I would like to convert the value 1101 to a 1x4 [1,1,0,1] in simulink
0 件のコメント
回答 (1 件)
Moe_2015
2022 年 9 月 8 日
You can do this by placing a matlab function block in Simulink. Your function should look like below. Connect your input signal (that has 1101) and the output will be a vector [1,1,0,1]
function vector = n_to_vector(n)
vector = num2str(n) - '0';
end
5 件のコメント
Moe_2015
2022 年 9 月 8 日
編集済み: Moe_2015
2022 年 9 月 8 日
sorry I realize now that simulink may have trouble with this. I have tried the below in Simulink and it worked. I borrowed a different way to compute this from Jan located here: https://www.mathworks.com/matlabcentral/answers/155622-hi-guys-i-need-help-splitting-a-number-into-its-individual-parts-and-then-add-them-e-g-the-number#answer_382856
so make your function look as below. In Ports and Data Manager, you will need to select vector (which is your output from the block) and check the variable size box and make the Size [1 4]. Also, in the settings (gear icon Configuration Parameters), you need to change solver to Fixed-step
function vector = n_to_vector(n)
m = floor(log10(n));
vector = mod(floor(n ./ 10 .^ (m:-1:0)), 10);
end
Walter Roberson
2022 年 9 月 8 日
assert(n >0 && n <= intmax('uint64'));
longest_possible_integer = 20;
charvec = blanks(longest_possible_integer);
vector = zeros(1, longest_possible_integer);
coder.varsize('charvec', 'vector', [1 longest_possible_integer]);
charvec = sprintf('%u', n);
vector = charvec - '0';
Here, longest_possible_integer = length(sprintf('%u', intmax('uint64'))) . Any input that is large magnitude than that will get converted in scientific notation by sprintf() and the process will fail
参考
カテゴリ
Help Center および File Exchange で Block Libraries についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!