How would I add a label to a variable?

5 ビュー (過去 30 日間)
David McCaffrey
David McCaffrey 2021 年 1 月 30 日
編集済み: Les Beckham 2021 年 1 月 30 日
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 日
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 日
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).

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by