Matlab toString equivalent? - matlab

Is there any way to convert any object to it's string representation in Matlab?
I tried
matlab.unittest.diagnostics.ConstraintDiagnostic.getDisplayableString
but sometimes it produces HTML code like this
0×0 empty char array
Is it possible to get only plain text in result?

It's not clear exactly what you want, but I use this kind of call for generating general purpose (text) error messages when the object type can vary. It calls disp() and captures the text output:
x = containers.Map({'A','B'}, [1,2]); % Example object - could be anything
s = evalc('disp(x)');
Now this uses evalc() which is rather clumsy and is never going to be quick and the 'x' is buried in a string. But it is convenient....

Related

How MATLAB's "if" function handles multiple inputs

I ran a quick test to see how if deals with multiple input values. It appears that the default behavior is to apply and to the collection of values, but I couldn't find any documentation. Can anyone confirm or provide a counterexample?
>> if([1,1,1]) disp(sprintf('hi'));end;
hi
>> if([1]) disp(sprintf('hi'));end;
hi
>> if([1,1,0]) disp(sprintf('hi'));end;
EDIT: to clarify, I don't intend to try to use this "feature," but wanted to be sure I knew how erroneous input would be handled. Suppose, for example, your code read
if(my_function) and the (badly written) my_function usually returns a single value but occasionally returns multiple values. Good practice, of course , would parse the returned values appropriately and feed a single value to if.
I don't find any practical reason to create an if statement which depends on anything but a scalar.
Regarding what's done in MATLAB practically?
You may assume MATLAB applies the function all on the input of the if statement.
This will hold as intuition given the array is non empty.
For example, if we have array - array4Example which is not empty, the statement if on the array - if(array4Example) is equivalent of the statement if on the scalar - if(all(array4Example(:))).
This matches the documentation if the if function.

Passing multiple inputs into a MATLAB function via loop?

I have multiple variables var_1, var_2, var_3....var_9 (they are named like that) that I want to pass in a function. All of the variables are saved in the workspace. The function takes 2 variables, and spits out an output. I want to compare var_1 with all the variables, including itself, so I prefer to automate it in a loop.
So I want to execute
function(var_1,var_1)--> display answer, function(var_1,var_2)--> display answer...function(var_1,var_9)-->display answer all at once in a loop. I've tried the following, with no luck:
for i=1:7
functionname(var_1,var_'num2str(i)')
end
Where did I go wrong?
You cannot make a dynamic variable name directly. But you can use the eval-function to evaluate an expression as a string. The string can be generated with sprintf and replaces %d with your value.
for i=1:7
eval(sprintf('functionname(var_1,var_%d)', i));
end
But: Whenever you can, you should avoid using the eval function. A much better solution is to use a cell array for this purpose. In the documentation of Matlab there is a whole article about the why and possible alternatives. To make it short, here is the code that uses a cell array:
arr = {val_1, val_2, val_3, val_4, val_5, val_6, val_7, val_8, val_9};
for i = 1:length(arr)
functionname(arr{1},arr{i})
end

How can I make the value of an expression equal to a second return value of another expression

Is there an idiomatic way in Matlab to bind the value of an expression to the nth return value of another expression?
For example, say I want an array of indices corresponding to the maximum value of a number of vectors stored in a cell array. I can do that by
function I = max_index(varargin)
[~,I]=max(varargin{:});
cellfun(#max_index, my_data);
But this requires one to define a function (max_index) specific for each case one wants to select a particular return value in an expression. I can of course define a generic function that does what I want:
function y = nth_return(n,fun,varargin)
[vals{1:n}] = fun(varargin{:});
y = vals{n};
And call it like:
cellfun(#(x) nth_return(2,#max,x), my_data)
Adding such functions, however, makes code snippets less portable and harder to understand. Is there an idiomatic to achieve the same result without having to rely on the custom nth_return function?
This is as far as I know not possible in another way as with the solutions you mention. So just use the syntax:
[~,I]=max(var);
Or indeed create an extra function. But I would also suggest against this. Just write the extra line of code, in case you want to use the output in another function. I found two earlier questions on stackoverflow, which adress the same topic, and seem to confirm that this is not possible.
Skipping outputs with anonymous function in MATLAB
How to elegantly ignore some return values of a MATLAB function?
The reason why the ~ operator was added to MATLAB some versions ago was to prevent you from saving variables you do not need. If there would be a syntax like the one you are searching for, this would not have been necessary.

get string of enum - matlab coder

I have an enum like this:
classdef(Enumeration) bla_type < int32
enumeration
bla_one(1)
bla_2(2)
end
end
I can get the 'string representation of an element' like this:
char(bla_type.bla_one)
=>
bla_one
Unfortunately, matlab coder does not like this. Are there any alternatives?
There's no elegant built-in way in Coder to do this; the enumerated type becomes a standard enum in C, and the enumeration function in MATLAB is unavailable in Coder. The simplest, but unpleasant, way to do it is to create a function with a switch statement with the manually populated string names. It's not nice, since now you have to maintain the names in two places.
However, one way that does work nicely is to use one of the more powerful features of Coder: coder.const.
The solution is to have a function that creates a table of the enumeration members and their values. This function itself cannot be compiled, but rather is called during compilation to build a lookup table in the resulting C code. We can use this lookup table in a Coder compatible function to get the data.
Imagine we have an enumerated type like this (in someenum.m):
classdef someenum < int32 %#codegen
enumeration
First_thing (0)
Second_thing (2)
Another_thing (3)
No_thing (4000)
end
end
We also then have the build-time function called 'buildsomeenum2name.m':
function [namearray, memberidx] = buildsomeenum2name
%BUILDSOMEENUM2NAME Compile-time creation of lookup table for someenum
% THIS FUNCTION IS NOT CODER COMPATIBLE, BUT IS CALLED DURING COMPILE
% TO CREATE A LOOKUP TABLE.
[members, names]=enumeration('someenum');
maxlen = 0;
for i=1:numel(names)
maxlen = max(maxlen, numel(names{i}));
end
namearray = char(zeros(numel(names), maxlen));
for i=1:numel(names)
namearray(i, 1:numel(names{i})) = names{i};
end
memberidx = int32(members); %#ok<NASGU>
end
When buildsomeenum2name is called in MATLAB, it creates an array of string names of all the members of the enumerated type and another vector list of their numeric values in the same order.
Here's the cool part. MATLAB Coder can evaluate functions at build time and turn them into constants. These constants become literals in the resulting C code, rather than actual code. Since the functions are evaluated at build time, the enumeration information is put into a nice table, therefore if we make a Coder-compatible lookup function, we can use it to convert the member types into a string. We'll call this function 'someenum2name.m':
function name = someenum2name(enum) %#codegen
%SOMEENUM2NAME Get the string name of an enumerated type
% The following line loads namearray and memberidx with constant arrays
coder.extrinsic('buildsomeenum2name');
[namearray, memberidx] = coder.const(#buildsomeenum2name);
% First find the index of the enumerated type in the memberidx vector
index = find(memberidx==int32(enum));
if isempty(index)
name = 'UNKNOWN';
return;
end
name = deblank(namearray(index,:));
end
This function uses the coder.const command to evaluate buildsomeenum2name at compile time and create the lookup tables. We have to instruct Coder not to try to compile buildsomeenum2name, so use the coder.extrinsic command to tell it to ignore the function. Then someenum2name can look up the index for the string and pull it out (deblank is used because the strings in the array have trailing 0's that need to be pulled out.) The function someenum2name can be called both within MATLAB and in Coder compiled code.
This method keeps everything in-sync, so if you ever add a new member to the enum or rearrange them, the coder.const function will make sure that the values are rebuilt in the output code so that someenum2name works.
At the command line, this looks like:
>> someenum2name(someenum.No_thing)
ans =
No_thing
Try [~,s]=enumeration('bla_type'). You get a cell array of strings containing the name of elements in s. So bla_one will be in s{1}. Don't know whether that is supported by MATLAB coder though.

What kind of data type is this?

In an class header I have seen something like this:
enum {
kAudioSessionProperty_PreferredHardwareSampleRate = 'hwsr', // Float64
kAudioSessionProperty_PreferredHardwareIOBufferDuration = 'iobd' // Float32
};
Now I wonder what data type such an kAudioSessionProperty_PreferredHardwareSampleRate actually is?
I mean this looks like plain old C, but in Objective-C I would write #"hwsr" if I wanted to make it a string.
I want to pass such an "constant" or "enum thing" as argument to an method.
This converts to an UInt32 enum value using the ASCII value of each of the entries. This style have been around for a long time in Mac OS headers.
'hwsr' has the same value as if you had written 0x68777372, but is a lot more reader friendly. If you used the #"hwsr" style instead you would need more than 4 bytes to represent the same.
The advantage of using this style is that you are actually able to quickly identify the content of a raw data stream if you can see the ASCII values of it.