eval not working after using horzcat matlab - matlab

im trying to make a script to be able to calculate a vector of numbers and math symbols to convert back to a single string
im using eval() function and example would be
str = '4*2'
eval(str)
and the result would be
ans =
8
but when i create into a vector and convert back using horzcat the result won't work.
Number = [52 42 50]
Number1 = (mat2str(char(Number)))
str = horzcat(Number1)
eval(str)
and i would get
ans =
4*2
can anyone help me find the problem with the script?

Your problem is with the mat2str command. This is unecesarry. The char command already returns a string. You end up with a string in a string, so when you eval in your code, you just display the inner string.

First - You should not use eval!
Second, there is no need in horzcat and mat2str in your code. Just write:
str = char(Number)

Related

Creating a function with variable number of inputs?

I am trying to define the following function in MATLAB:
file = #(var1,var2,var3,var4) ['var1=' num2str(var1) 'var2=' num2str(var2) 'var3=' num2str(var3) 'var4=' num2str(var4)'];
However, I want the function to expand as I add more parameters; if I wanted to add the variable vark, I want the function to be:
file = #(var1,var2,var3,var4,vark) ['var1=' num2str(var1) 'var2=' num2str(var2) 'var3=' num2str(var3) 'var4=' num2str(var4) 'vark=' num2str(vark)'];
Is there a systematic way to do this?
Use fprintf with varargin for this:
f = #(varargin) fprintf('var%i= %i\n', [(1:numel(varargin));[varargin{:}]])
f(5,6,7,88)
var1= 5
var2= 6
var3= 7
var4= 88
The format I've used is: 'var%i= %i\n'. This means it will first write var then %i says it should input an integer. Thereafter it should write = followed by a new number: %i and a newline \n.
It will choose the integer in odd positions for var%i and integers in the even positions for the actual number. Since the linear index in MATLAB goes column for column we place the vector [1 2 3 4 5 ...] on top, and the content of the variable in the second row.
By the way: If you actually want it on the format you specified in the question, skip the \n:
f = #(varargin) fprintf('var%i= %i', [(1:numel(varargin));[varargin{:}]])
f(6,12,3,15,5553)
var1= 6var2= 12var3= 3var4= 15var5= 5553
Also, you can change the second %i to floats (%f), doubles (%d) etc.
If you want to use actual variable names var1, var2, var3, ... in your input then I can only say one thing: Don't! It's a horrible idea. Use cells, structs, or anything else than numbered variable names.
Just to be crytsal clear: Don't use the output from this in MATLAB in combination with eval! eval is evil. The Mathworks actually warns you about this in the official documentation!
How about calling the function as many times as the number of parameters? I wrote this considering the specific form of the character string returned by your function where k is assumed to be the index of the 'kth' variable to be entered. Array var can be the list of your numeric parameters.
file=#(var,i)[strcat('var',num2str(i),'=') num2str(var) ];
var=[2,3,4,5];
str='';
for i=1:length(var);
str=strcat(str,file(var(i),i));
end
If you want a function to accept a flexible number of input arguments, you need varargin.
In case you want the final string to be composed of the names of your variables as in your workspace, I found no way, since you need varargin and then it looks impossible. But if you are fine with having var1, var2 in your string, you can define this function and then use it:
function str = strgen(varargin)
str = '';
for ii = 1:numel(varargin);
str = sprintf('%s var%d = %s', str, ii, num2str(varargin{ii}));
end
str = str(2:end); % to remove the initial blank space
It is also compatible with strings. Testing it:
% A = pi;
% B = 'Hello!';
strgen(A, B)
ans =
var1 = 3.1416 var2 = Hello!

Matlab and string latex format

In Matlab, I need to format a latex string containing a numeric variable.
The string is like: foo1 , where 1 is contained in variable X and must be subscript.
This line works if I write directly the value of variable
str = texlabel('foo_{1}')
I'm wondering how to insert the X instead of the value.
In fact this line
str = texlabel('foo_{X}')'
produce, of course, fooX
Thanks
The quickest method would be to include a call to sprintf:
X = 1;
str = texlabel(sprintf('foo_{%u}', X));
Which returns:
str =
{foo}_{{2}}
Which we can plot real quick with text(0.1, 0.1, str):

Importing data with engineering notation into Matlab

I've got a .xls file and I want to import it into Matlab by xlsread function..I get NaNs for numbers with engineering notation..like I get NaNs for 15.252 B or 1.25 M
Any suggestions?
Update: I can use [num,txt,raw] = xlsread('...') and the raw one is exactly what I want but how can I replace the Ms with (*106)?
First you could extract everything from excel in a cell array using
[~,~,raw] = xlsread('MyExcelFilename.xlsx')
Then you could write a simple function that returns a number from the string based on 'B', 'M' and so on. Here is such an example:
function mynumber = myfunc( mystring )
% get the numeric part
my_cell = regexp(mystring,'[0-9.]+','match');
mynumber = str2double(my_cell{1});
% get ending characters
my_cell = regexp(mystring,'[A-z]+','match');
mychars = my_cell{1};
% multiply the number based on char
switch mychars
case 'B'
mynumber = mynumber*1e9;
case 'M'
mynumber = mynumber*1e6;
otherwise
end
end
Of course there are other methods to split the numeric string from the rest, use what you want. For more info see the regexp documentation. Finally use cellfun to convert cell array to numeric array:
my_array = cellfun(#myfunc,raw);
EDIT:
Matlab does not offer any built-in formatting of strings in engineering format.
Source: http://se.mathworks.com/matlabcentral/answers/892-engineering-notation-printed-into-files
In the source you will find also function which would be helpful for you.

Why doesn't strcmp recognize two seemingly equal strings as the same?

Below is the output from the Matlab's console. Both of the strings are the same: '#TBMA3'. Yet Matlab's strcmp function returns 0 when comparing them. Why?
K>> str='#TBMA3'
str =
#TBMA3
K>> method.fhandle
ans =
#TBMA3
K>> strcmp(method.fhandle, str)
ans =
0
The most likely reason is that method.fhandle is not a string, but a function handle. Check if class(method.fhandle) gives
ans =
function_handle
In that case, the comparison gives 0 because a string (str) cannot be equal to a function handle (method.fhandle).
In order to check for equality, you would need to convert method.fhandle to a string, or str to a function handle. The first option is not adequate, because char(function_handle) would give 'TBMS3', without '#'. So use the second option, and compare using isequal:
isequal(method.fhandle, str2func(str))
should give 1.†
† This isequal comparison works because both method.fhandle and str2func(str) point to the same already-defined function TBMA3. Compare with f = #(x)x; g = #(x)x, isequal(f,g), which gives 0. This behaviour is explained in the documentation. Thanks to #knedlsepp for helping clarify this.

x = disp(y) : "Too many output arguments"

I'm looking for a completely general way to convert any value to a string in MATLAB.
Basically, I want to be able to write something like
x = disp(y);
The above fails with the error Too many output arguments. (I was not able to find the source code for disp.)
Is there a single MATLAB function for converting any value into a string?
(Note that this function should behave like the identity when passed a string.)
Basically I'm looking for MATLAB's equivalent of Python's str. I thought it might be char, but (for example) char(Inf) fails to produce anything like the string 'Inf'. (Note: that was just an example. It does not begin to cover all the possibilities.)
pm89's answer has the right idea, but doesn't work because evalc requires a string as input. I suggest making your own function like so:
function str = anything2string(thing)
str = evalc('disp(thing)');
It works for anything that Matlab can display:
>> anything2string(3)
ans =
3
>> anything2string(Inf)
ans =
Inf
>> anything2string('hi')
ans =
hi
>> anything2string(1:4)
ans =
1 2 3 4
It's not quite the same as Python's str, but num2str works with Inf and handles strings as input.
num2str(Inf)
ans = Inf
num2str('some string')
ans = some string
You could get the exact same string as you see in your command window using evalc (evaluate and capture the result):
x = evalc('disp(y)'); % y could be anything displayable by Matlab!