How to sum up all numbers in an array - groovy

I have an array which outputs the following:
charges = [5.00, 26.00, 8.00, 4.00, 4.00, -8.00, 54.00, 52.48]
When I try to perform a sum using this:
charges.sum()
It gives me:
5.0026.008.004.004.00-8.0054.0052.48
I am assuming I need to convert it from a string to a float so I did:
Float.valueOf((String) charges.sum())
and it gives me an error which states 'multiple points'.
My question is how do I add all of these figures up?

If your list is actually of strings, you can quickly do the conversion with sum()'s closure form.
charges.sum { it.toBigDecimal() }

It is unclear what your list has in it, it seems like the entries in your list are actually strings (since sum concatenates them), or something that prints a string value (has a toString method that returns a string showing the value so you think it is numeric even though it isn’t) . They are definitely not numeric, so convert each of them to a numeric type before summing:
charges.collect { new BigDecimal(it.toString()) }.sum()
(What your code was doing was concatenating the string values together, then converting that to a numeric type.)

You must delete the cast (String)
Float.valueOf(charges.sum())

Related

Reading a comma-separated string (not text file) in Matlab

I want to read a string in Matlab (not an external text file) which has numerical values separated by commas, such as
a = {'1,2,3'}
and I'd like to store it in a vector as numbers. Is there any function which does that? I only find processes and functions used to do that with text files.
I think you're looking for sscanf
A = sscanf(str,formatSpec) reads data from str, converts it according
to the format specified by formatSpec, and returns the results in an
array. str is either a character array or a string scalar.
You can try the str2num function:
vec = str2num('1,2,3')
If you have to use the cell a, per your example, it would be: vec=str2num(a{1})
There are some security warnings in the documentation to consider so be cognizant of how your code is being employed.
Another, more flexible, option is textscan. It can handle strings as well as file handles.
Here's an example:
cellResult = textscan('1,2,3', '%f','delimiter',',');
vec = cellResult{1};
I will use the eval function to "evaluate" the vector. If that is the structure, I will also use the cell2mat to get the '1,2,3' text (this can be approached by other methods too.
% Generate the variable "a" that contains the "vector"
a = {'1,2,3'};
% Generate the vector using the eval function
myVector = eval(['[' cell2mat(a) ']']);
Let me know if this solution works for you

Trying to compare a string to an array and return string, instead of a value

I'm trying to write a function that looks at the string in a cell and depending on the first 2-3 letters write a string in the cell next to it.
For example:
"LSH T1402A" should return "High-Level Safety"
"FI P1402A" should return "Flow Indicator"
(I know in the second case there are only 2 symbols, but in the array I would include the space in the string so that shouldn't give any problems)
At first I was thinking of using an IF function, but quickly abandoned the idea because it would become too lengthy.(many different strings/types of sensors)
Currently I've broken down my problem in 4 steps
Read String
Return first 3 symbols
Compare to array/matrix
Write string corresponding.
The first two parts I think I can solve by using "=LEFT(TRIM([CEL]);3) but I am stuck on how to compare it to an array. The MATCH function comes close but only returns a value for which position the cell is on I believe?
Does anyone have an idea how I should continue solving this problem? Many thanks!
If your array was say in G1:H10 then you could
lookup your 3 character code in G1:G10 using MATCH
return the corresponding value from H1:H10 using INDEX
example
=INDEX(H1:H10,MATCH(LEFT(A1,3),G1:G10,0))
Function will return a #N/A if no match is found

How do I only replace the first instance of a number in a string?

I am taking a description of the weather using rainfall in millimeters and converting it to inches. I have worked out to calculate the rainfall in inches and replace it in the string. Because the description also has other numbers, I want to only replace the first instance of the number I converted (rainfall is listed first).
weatherConverted = weatherConverted.stringByReplacingOccurrencesOfString("\(precipitationInMillimeters)", withString: "\(precipitationInInches)")
precipitationInMillimeters is an Integer, hence the escape sequence. I know that the function rangeOfString(_:) will return the range of the first instance of the string I put in it, but I don't know the proper syntax for calling that function and getting it to return to the range parameter.

I am trying to display variable names and num2str representations of their values in matlab

I am trying to produce the following:The new values of x and y are -4 and 7, respectively, using the disp and num2str commands. I tried to do this disp('The new values of x and y are num2str(x) and num2str(y) respectively'), but it gave num2str instead of the appropriate values. What should I do?
Like Colin mentioned, one option would be converting the numbers to strings using num2str, concatenating all strings manually and feeding the final result into disp. Unfortunately, it can get very awkward and tedious, especially when you have a lot of numbers to print.
Instead, you can harness the power of sprintf, which is very similar in MATLAB to its C programming language counterpart. This produces shorter, more elegant statements, for instance:
disp(sprintf('The new values of x and y are %d and %d respectively', x, y))
You can control how variables are displayed using the format specifiers. For instance, if x is not necessarily an integer, you can use %.4f, for example, instead of %d.
EDIT: like Jonas pointed out, you can also use fprintf(...) instead of disp(sprintf(...)).
Try:
disp(['The new values of x and y are ', num2str(x), ' and ', num2str(y), ', respectively']);
You can actually omit the commas too, but IMHO they make the code more readable.
By the way, what I've done here is concatenated 5 strings together to form one string, and then fed that single string into the disp function. Notice that I essentially concatenated the string using the same syntax as you might use with numerical matrices, ie [x, y, z]. The reason I can do this is that matlab stores character strings internally AS numeric row vectors, with each character denoting an element. Thus the above operation is essentially concatenating 5 numeric row vectors horizontally!
One further point: Your code failed because matlab treated your num2str(x) as a string and not as a function. After all, you might legitimately want to print "num2str(x)", rather than evaluate this using a function call. In my code, the first, third and fifth strings are defined as strings, while the second and fourth are functions which evaluate to strings.

Can you treat a string as one object in a list in MATLAB?

I would like to make a list of strings in MATLAB using the example below:
x = ['fun', 'today', 'sunny']
I want to be able to call x(1) and have it return 'fun', but instead I keep getting 'f'.
Also, is there a way to add a string to a list without getting the list giving back a number where the string should be? I have tried using str2double and a few other things. It seems like both of these thing should be possible to do in MATLAB.
The easiest way to store a list of strings that have different lengths is to use cell arrays. For example:
>> x = {'fun', 'today', 'sunny'}; %# Create a cell array of strings
>> x{1} %# Get the string from the first cell
ans =
fun
It's kind of a kludgy workaround, but
x = strsplit('fun.today.sunny', ',')
produces a list with individual, callable strings.

Resources