Addition of numbers in array

조회 수: 1 (최근 30일)
Muhammad Usman
Muhammad Usman 2021년 2월 13일
댓글: Steven Lord 2021년 2월 16일
Lets' say I have 2 vectors:
x = [7 4 6];
y = [1 4 4];
But these are not just vector consider them as A number, i.e., 746 and 144. Now I want to add these numbers (as we do on paper, carry method).
so the answer should be 890.
and want display like:
7 4 6
1 4 4
-----
8 9 0
Please help me to code.
Thanks

채택된 답변

Ameer Hamza
Ameer Hamza 2021년 2월 13일
This is one way
x = [7 4 6];
y = [1 4 4];
z = sscanf(sprintf('%d',x),'%d')+sscanf(sprintf('%d',y),'%d')
  댓글 수: 4
Muhammad Usman
Muhammad Usman 2021년 2월 15일
@KALYAN ACHARJYA, I am following your lines of code, but generating error when I do:
x = randi([0,9],1,20);
y = randi([0,9],1,20);
x_new = str2double(sprintf('%d',x));
y_new = str2double(sprintf('%d',y));
result = num2str(x_new+y_new) - '0';
fprintf('%4d',x);
fprintf('\n');
fprintf('%4d',y);
fprintf('\n');
disp('+');
disp('-------------------------------------------------------------------------')
fprintf('%d',result);
fprintf('\n')
The ouput I get (which is wrong):
9 6 1 3 0 5 4 9 8 4 8 1 3 9 9 7 6 3 9 1
7 6 8 3 7 8 3 5 9 5 3 6 3 7 4 4 6 9 3 8
+
-------------------------------------------------------------------------
1-272968385801777453-520
can you please mention the mistake in running these lines. And help me to align (with same gap spaces) the result
Steven Lord
Steven Lord 2021년 2월 16일
Your numbers are too large to guarantee that they can be stored exactly as double precision numbers.
x = 96130549848139976391;
rem(x, 10) % ones digit
ans = 8
spacing = eps(x)
spacing = 16384
The spacing between consecutive representable numbers in the vicinity of x is 16,384. It is too large even to be stored exactly as a uint64 number.
y = uint64(96130549848139976391) % Saturated at intmax
y = uint64 18446744073709551615
You will need to store your numbers and perform calculations in arbitrary precision arithmetic, like in Symbolic Math Toolbox.
s = sym('96130549848139976391')
s = 
96130549848139976391

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Simulink에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by