How would I add a label to a variable?
6 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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?
0 Kommentare
Antworten (2)
Walter Roberson
am 30 Jan. 2021
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
0 Kommentare
Les Beckham
am 30 Jan. 2021
Bearbeitet: Les Beckham
am 30 Jan. 2021
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).
0 Kommentare
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!