How would I add a label to a variable?

Let's say I'm programming a converter, like miles to kilometers, how do I make it so when I type it all out the answer comes out as "10 kilometers" instead of just the number 10?

답변 (2개)

Walter Roberson
Walter Roberson 2021년 1월 30일

0 개 추천

https://www.mathworks.com/help/symbolic/units-list.html
units can be attached to symbolic computation, where they end up being treated like multiplication by a variable a lot of the time.
units are not supported in numeric work without the symbolic toolbox... Well, except in Simscape and derivatives such as SimBiology
Les Beckham
Les Beckham 2021년 1월 30일
편집: Les Beckham 2021년 1월 30일

0 개 추천

Without extra toolboxes, and assuming that you are programming your 'converter' as a function and you wish to print the results as well as return them to the caller, you might use the fprintf() function within your conversion functions. For example:
% test_mi2km_converters.m
%
% https://www.mathworks.com/matlabcentral/answers/731023-how-would-i-add-a-label-to-a-variable?s_tid=srchtitle
distance_mi = 10; % initially in miles
distance_km = mi2km(distance_mi);
distance_mi_check = km2mi(distance_km);
distance_km_check = mi2km(distance_mi_check);
function km = mi2km(mi)
km = ((mi*5280) * 0.3048) / 1000;
fprintf('%f miles = %f kilometers\n', mi, km);
end
function mi = km2mi(km)
mi = ((km*1000) / 0.3048) / 5280;
fprintf('%f kilometers = %f miles\n', km, mi);
end
Here is the resulting output:
>> test_mi2km_converters
10.000000 miles = 16.093440 kilometers
16.093440 kilometers = 10.000000 miles
10.000000 miles = 16.093440 kilometers
Adapt as desired. Note that this code requires Matlab release 2016b or later (when they started allowing functions to be defined inside of scripts).

카테고리

도움말 센터File Exchange에서 Data Import and Analysis에 대해 자세히 알아보기

태그

질문:

2021년 1월 30일

편집:

2021년 1월 30일

Community Treasure Hunt

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

Start Hunting!

Translated by