matlab: converting a vector to a cell array of strings - matlab

I'm sure there's a way to do this but I don't know what it is.
Suppose I have a vector
v = [1.02 2.03 3.04];
and I want to convert this to a cell array using a format string for each element:
' %.3f'
(3 spaces before the %.3f)
How can I do this? I tried the following approach, but I get an error:
>> f1 = #(x) sprintf(' %.3f',x);
>> cellfun(f1, num2cell(v))
??? Error using ==> cellfun
Non-scalar in Uniform output, at index 1, output 1.
Set 'UniformOutput' to false.

As stated in the error, just provide the parameter of UniformOutput as false
cellfun(f1, num2cell(v), 'UniformOutput', false)
ans =
' 1.020' ' 2.030' ' 3.040'

Here is another solution:
>> v = [1.02 2.03 3.04];
>> strcat({' '}, num2str(v(:),'%.3f'))
ans =
' 1.020'
' 2.030'
' 3.040'
Obviously you can transpose the result if you want a row vector.

You can also use the {} syntax:
cellfun(#(x){f1(x)}, num2cell(v))
Also check out : Applying a function on array that returns outputs with different size in a vectorized manner

Related

MATLAB: Trying to not display the logical array in this code

This is a function that checks if the array that is inputted is a square matrix. The function is doing what I want, namely checking if the array is square, but it also outputs the logical array that I am using to check if the number of rows equals the number of columns.
function isSquare = checkSquare(x)
[rnum, cnum] = size(x);
isSquare = rnum == cnum;
if isSquare == 1
fprintf('True')
else
fprintf('False')
end
end
I think it's because you're running the function without putting a semicolon at the end.
>> checksquare(zeros(4,4))
True
ans =
logical
1
>>
Instead, try this.
>> checksquare(zeros(4,4));
True>>
It would be nicer for the formatting to print a newline character after True or False. Change fprintf('True') to fprintf('True\n') and fprintf('False') to fprintf('False\n') and you'll get the following result.
>> checksquare(zeros(4,4));
True
>>

Matlab vector Printing

How do i print a vector in matlab with also something before the values. For example i have a vector with the following values A' = [1 2 3]. I want to print it out in such a way that the output will be
w0 = 1
w1 = 2
w2 = 3
How do i do this?
Can i do this using a loop?
I am using the following code and i am not getting the right output
for qux = 1:3
fprintf('w%i=%.4lf\n',qux-1,answ);
end
Output:
w0=w1=w2
Your format string is not formed properly. Specifically '%.4lf' should be '%.4f'. Additionally, the third input to fprintf should be A(qux) to access the value in A.
for qux = 1:3
fprintf('w%i=%.4f\n', qux-1, A(qux));
end
I would, however, recommend using '%g' to use a format that optimizes the display of each number. Additionally, you could remove the for loop and do something like
A = [1, 2, 3];
fprintf('w%i = %g\n', [0:numel(A)-1; A])
If I have understand the question correctly, I think that you could do that with the following code:
for i = 1:3
disp(['w' num2str(A(i)-1) '=' num2str(A(i))]);
end
Using disp and num2str you could get the following output:
w0=1
w1=2
w2=3

Using num2str with matrices in Octave

Having issue with the num2str function in Octave.
My code:
>> alpha = zeros(1,length(alpha));
>> legendInfo = zeros(1,length(alpha));
>> legendInfo(1) = num2str(alpha(1));
Error Message:
error: A(I) = X: X must have the same size as I
I've been trying to follow this link to no avail: Link
Update:
Based on suggestion, I have implemented the following code and have received the following error message:
>> labelInfo = cell(1,numel(alpha))
>> labelInfo{1} = num2str(alpha{1});
error: matrix cannot be indexed with {
error: evaluating argument list element number 1
ANSWER
The answer provided was accurate with one tweak:
alpha{1} (Incorrect syntax)
alpha(1) (Correct Syntax)
Parantheses rather than curly braces.
Thanks!
You have initialized legendInfo to be a numeric array the same size as alpha. When you convert alpha(1) to a string, it is possibly more than 1 character long (i.e. alpha(1) > 9) which is obviously not going to fit into a single element in an array.
length(num2str(10))
% 2
length(legendInfo(1))
% 1
Also, even if num2str(alpha(1)) yields a string that has a length of 1, it will implicitly convert it to a number (it's ASCII representation) which is likely not what you want.
legendInfo = zeros(1, numel(alpha));
legendInfo(1) = num2str(1);
% 49 0 0
Rather than a numeric array, you likely want a cell array to hold the legend info since you will have strings of varying lengths.
legendInfo = cell(1, numel(alpha));
legendInfo{1} = num2str(alpha{1});
If you look closely at the post you have linked, you'll see that they use the curly brackets {} to perform assignment rather than parentheses () indicating that they are creating a cell array.

Any trim functions in matlab?

If I have an input like [1 2 3; 4.0 c] and I want it to output it like 1234.0c in matlab. What function can I use ? I am looking for something like trim in php.
Any idea ?
Thanks
You can use this to remove any number of spaces from inside of a string:
>> a = char(' he llo wor ld ');
>> a(isspace(a)) = [] %replaces all of the space with nothing
a =
helloworld
You can use isstrprop function with approppriate categories. For your case,
>> str = '1 2 3; 4.0 c';
>> str(isstrprop(str, 'alphanum') | str == '.')
ans =
1234.0c
You can use functions like isletter, isnumeric, etc. if you like.
Besides, you can create your own function in one line as follows
>> myTrim = #(x)(x(isstrprop(x, 'alphanum') | x == '.'));
>> myTrim(str)
ans =
1234.0c
Note that you ask [1 2 3; 4.0 c] as an input which is not a proper syntax for MATLAB. I assumed you wanted to ask for a string. In addition, trim actually implies removing leading and trailing white space from a string and there is strtrim for this in MATLAB.
It is not a valid MATLAB argument.
But if you have something like
a = ['1', '2' ,'3'; '4', '.','c'];
you can use
a(:)'
to get
142.3c
or
a = a';
a(:)'
to get
123.4c

Matlab sprintf formatting

EDIT: I've reworded the question to be clearer.
Does anyone know a clever way to get sprintf to print "%.6f with trailing zeros elminated"? This is what I'm looking for:
sprintf('%somemagic ', [12345678 123.45])
ans = 1234578 123.45
where %somemagic is some magical specifier. None of the formats seem to work.
% no trailing zeros, but scientific for big nums
sprintf('%g ', [12345678 123.45])
ans = 1.23457e+007 123.45
% not approp for floats
sprintf('%d ', [12345678 123.45])
ans = 12345678 1.234500e+002
% trailing zeros
sprintf('%f ', [12345678 123.45])
ans = 12345678.000000 123.450000
% cannot specify sig figs after decimal (combo of gnovice's approaches)
mat = [12345678 123.45 123.456789012345];
for j = 1:length(mat)
fprintf('%s ', strrep(num2str(mat(j),20), ' ', ''));
end
I don't think there is a way to do it other than looping through each element and changing the specifier based off of mod(x,1)==0 or using regexp to remove trailing zeros. But you never know, the crowd is more clever than I.
My actual application is to print out the array elements in an html table. This is my current clunky solution:
for j = 1:length(mat)
if mod(mat(j),1) == 0
fprintf('<td>%d</td>', mat(j));
else
fprintf('<td>%g</td>', mat(j));
end
end
EDIT: Updated to address the edited question...
I don't think there's any way to do it with a particular format string for SPRINTF, but you could instead try this non-loop approach using the functions NUM2STR and REGEXPREP:
>> mat = [12345678 123.45 123.456789012345]; %# Sample data
>> str = num2str(mat,'<td>%.6f</td>'); %# Create the string
>> str = regexprep(str,{'\.?0+<','\s'},{'<',''}); %# Remove trailing zeroes
%# and whitespace
>> fprintf(str); %# Output the string
<td>12345678</td><td>123.45</td><td>123.456789</td> %# Output
The problem is that you're mixing an int with a float in an array. Matlab doesn't like that so it will convert your int to a float so that all elements in the array are of the same type. Look at doc sprintf: you're now forced to use %f, %e or %g on floats
Although I admit I like the STRREP method above (or below)