Convert integer value to a vector

I would like to convert the value 1101 to a 1x4 [1,1,0,1] in simulink

답변 (1개)

Moe_2015
Moe_2015 2022년 9월 8일

0 개 추천

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
Moe_2015 2022년 9월 8일
편집: Torsten 2022년 9월 8일
You can test this in your matlab command window:
n = 1101;
vector = num2str(n) - '0'
vector = 1×4
1 1 0 1
Adam s
Adam s 2022년 9월 8일
The function above gives this error
num2str is supported only for constant inputs. Consider using sprintf instead. Function 'SM_grid/MATLAB Function3' (#1110.42.52), line 2, column 10: "num2str(n)" Launch diagnostic report.
Component:MATLAB Function | Category:Coder error
Errors occurred during parsing of MATLAB function 'ssn_IEEE123_CompensatedStubline/SM_grid/MATLAB Function3'
Component:MATLAB Function | Category:Coder error
Simulink cannot determine sizes and/or types of the outputs for block 'ssn_IEEE123_CompensatedStubline/SM_grid/MATLAB Function3' due to errors in the block body, or limitations of the underlying analysis. The errors might be inaccurate. Fix the indicated errors, or explicitly specify sizes and/or types for all block outputs.
Adam s
Adam s 2022년 9월 8일
changing num2str() to sprintf() returns a value of 62
Moe_2015
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
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

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

카테고리

도움말 센터File Exchange에서 Modeling에 대해 자세히 알아보기

제품

릴리스

R2019b

질문:

2022년 9월 8일

댓글:

2022년 9월 8일

Community Treasure Hunt

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

Start Hunting!

Translated by