How to get Matlab to print both values and variable name

512 views (last 30 days)
Is there any way to get Matlab to print both the name of the variables along with their values? I know the disp command shows the values without the variable name and the fprintf command allows you to print a string with variables. But I'm trying to sort variables from highest to lowest and I want to get Matlab to print their corresponding variables rather than just giving me numbers. thanks!

Accepted Answer

Stephen23
Stephen23 on 27 Nov 2017
Edited: Stephen23 on 27 Nov 2017
Your approach is fundamentally flawed because you are storing meta-data in the variable names: trying to access that meta-data will make your code complex, slow, and hard to debug. Read this to know why:
Not only that but your idea of calculating the mean of each column separately is waste of MATLAB, which generally works most efficiently on entire arrays at once. In general you should keep data together as much as possible, not split it apart. Keeping data together makes processing it easier.
Much simpler would be to store the names as data in their own cell array (untested as you did not supply any data):
vec = mean(data,1);
C = {'Erie','Huron','Michigan','Ontario','Superior'};
[new,idx] = sort(vec);
D = C(idx); % sort the names into the same order
D(2,:) = num2cell(new);
fprintf('%10s %d\n',D{:})
I tested it using some fake data:
vec = [ 4, 2, 1, 3, 5];
C = {'Erie','Huron','Michigan','Ontario','Superior'};
[new,idx] = sort(vec);
D = C(idx); % sort the names into the same order
D(2,:) = num2cell(new);
fprintf('%10s %d\n',D{:})
which displays this:
Michigan 1
Huron 2
Ontario 3
Erie 4
Superior 5
So it sorted the data and names, and then printed them in the command window, exactly as you requested. And the complete code is only six lines... how did I do that? Simply by keeping the data together, and not putting meta-data into the variable names.

More Answers (2)

dpb
dpb on 27 Nov 2017
Couple of choice depending upon just how you want to use it...
As a function, can retrieve the passed variable name with inputname so can write something like the following (without any error checking, formatting, etc., etc., etc., ...)--
function dispwithname(varargin)
% DISPWITHNAME(X) -- Display scalar variable(s) in argument list with name(s)
for i=1:nargin
disp([inputname(i) '= ' num2str(varargin{i})])
end
Alternatively, you could capture the list of desired variables from who with an argument list including appropriate wildcard and then iterate over that list having rearranged the order from the default aplphanumeric sort to the desired numeric order by use of the optional indexing array variable returned by sort
Improvements to format and the like are probably near endless...
  1 Comment
Wojciech Kalinowski
Wojciech Kalinowski on 27 Nov 2022
That's a realy good code. I edited the code for numbers so that the decimal point is alligned and I thought I might share it. Unfortunataly, it does not work well with string/chars now.
function dispwithname(varargin)
% DISPWITHNAME(X) -- Display scalar variable(s) in argument list with name(s)
% finds the largest number before the decimal point
maxChar = 0;
bks2 = zeros(nargin,1); % number of blank space to align the decimal points
for i = 1:nargin
a1 = textscan(num2str(varargin{i}), '%s %s', 'delimiter','.');
bks2(i) = strlength(string(a1(1)));
if bks2(i) > maxChar
maxChar = bks2(i);
end
end
% displays the numbers aligned at the decimal point
for i=1:nargin
bks1 = blanks(4-length(inputname(i))); % number of blank spaces
disp([' ' inputname(i) bks1 ' = ' blanks(maxChar-bks2(i)) num2str(varargin{i})])
end
end
There probably is a more efficent way to do this.
example:
a = -123.0258;
b = 123.213521;
c = 128546.3;
d = -2354.213;
e = 0;
dispwithname(a,b,c,d,e);
output:
a = -123.0258
b = 123.2135
c = 128546.3
d = -2354.213
e = 0

Sign in to comment.


Image Analyst
Image Analyst on 27 Nov 2017
Just put the name of the variable on the line of code without anything else, no semicolon, etc. For example if your variable is myVar, DO NOT DO
disp(myVar);
DO this instead
myVar
  2 Comments
kami
kami on 27 Nov 2017
Hi, thanks for the help. But after I use the sort command the function only gives me values (from highest to lowest), what im trying to do is to get Matlab to find the corresponding variable name from the value and splay them together. something like
a=2
b=3
d=4
then when I ask Matlab where 2,3 and 4 is stored it would show me
a=2
b=3
d=4
what I have is
lake_Erie = mean(data(:,1));
lake_Huron= mean(data(:,2));
lake_Michigan = mean(data(:,3));
lake_Ontario = mean(data(:,4));
lake_Superior= mean(data(:,5));
lake_names =[lake_Erie,lake_Huron,lake_Michigan,lake_Ontario,lake_Superior];
z=sort(lake_names)
now I want to get Matlab to show me the lake names and the corresponding value after it sorts them, is that even possible to do?
dpb
dpb on 27 Nov 2017
Sure...
>> data=randn(10,5); % dummy valuess
>> lake_Erie = mean(data(:,1));
lake_Huron= mean(data(:,2));
lake_Michigan = mean(data(:,3));
lake_Ontario = mean(data(:,4));
lake_Superior= mean(data(:,5));
>>dispwithname(lake_Erie,lake_Huron,lake_Michigan,lake_Ontario,lake_Superior)
lake_Erie= -0.50798
lake_Huron= -0.10307
lake_Michigan= 0.018442
lake_Ontario= -0.29129
lake_Superior= 0.4192
>>
using the routine I showed earlier.
But, you don't even need to do that if use the alternate version I mentioned--
>> clear lake_names % get rid of one we don't want/need...
>> vnames=who('lake_*'); % get the list of variables of interest
>> for i=1:length(vnames)
fprintf('%s=%f\n',vnames{i},eval(vnames{i}))
end
lake_Erie=-0.507984
lake_Huron=-0.103066
lake_Michigan=0.018442
lake_Ontario=-0.291291
lake_Superior=0.419201
>>
Again, clean up format and other details to heart's content...

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!