I'm using Math.Net (http://numerics.mathdotnet.com/) to work with matrices.
I need a method that returns a matrix as a string.
So if my matrix looks like this:
{{1.0, 2}
{3 , 4}}
I need my return string to equal
"1 2 3 4"
Here is my code
var M = Matrix<double>.Build;
var mMatrix = M.DenseOfArray(new[,] {{ 1.0, 2 },
{ 3 , 4}});
StringBuilder builder = new StringBuilder();
foreach (var m in unitMatrix.Enumerate())
{
builder.Append(m + " ");
}
return builder.ToString();
This returns "1 3 2 4"
How do I make it return "1 2 3 4"?
You can enumerate row by row using mMatrix.EnumerateRows(), and then enumerate through all the values of each row. For example, you could write this as:
String.Join(" ", mMatrix.EnumerateRows().SelectMany(x => x.Enumerate()))
or if it is ok to build up an intermediate array:
String.Join(" ", mMatrix.ToRowWiseArray())
Alternatively you could use the existing string formatting functions, even though they are a bit weird to use, e.g.:
mMatrix.ToMatrixString(int.MaxValue,0,int.MaxValue,0,"","",""," "," ", x => x.ToString())
This has been bugging me for three days. I'm attempting to read text from a text field, check the length of the value is greater than zero (using the String method length), then create a loop. If the length is not greater than zero, I have to set an error message and an error flag (boolean variable to true). I've dug into the documentation for the String method but I can't seem to get length() to work for me. You can see my experimenting with the code. First time posting, sorry if I'm getting this wrong.
private void setShipmentProperties() {
ship.setEmployeeNum(empNumTF.getText());
if(ship.setEmployeeNum(String(length()) < 0)) {
isDataEntryError = true;
msgLbl.setText("Pay rate must be a numeric " + "value: 1, 2, 3...");
}
ship.setShipmentNum(shipNumTF.getText(this.length()));
if(this.length() < 0) {
isDataEntryError = true;
msgLbl.setText("Pay rate must be a numeric " + "value: 1, 2, 3...");
}
ship.setSupplierName(supplTF.getText());
if(ship.length() < 0) {
isDataEntryError = true;
msgLbl.setText("Pay rate must be a numeric " + "value: 1, 2, 3...");
}
}
A length can't be < 0. The length of a string can't be less than zero.
I tried to add a column named FTE containing this formula :
=I2/SUMPRODUCT(I:I,(M:M=M2) * (C:C=C2) * (N:N=N2))
This formula worked when applied in Excel, but when added from php, I just get an error:
maximum execution time calculation.php phpexcel
$assembly = $arrayWorksheet->addColValByRow($assembly, 'FTE', ['= I', '/SUMPRODUCT(I:I,(M:M=M', ')*(C:C=C', ')*(N:N=N'], '))');
// Output : =I2/SUMPRODUCT(I:I,(M:M=M2)*(C:C=C2)*(N:N=N2))
Sadly I can't figure out why. My initial formula was SUMIFS that I converted into SUMPRODUCT, because I know that SUMIFS isn't implemented yet.
function addColValByRow($worksheet, $title, $valArray, $finalVal = NULL) {
// Take the last column
$lastCol = key( array_slice( $worksheet[1], -1, 1, TRUE ) );
$newCol = ++$lastCol;
// tke the last cell
$lastCell = key( array_slice( $worksheet, -1, 1, TRUE ) );
$worksheet[1][$newCol] = $title;
for ($i = 2; $i <= $lastCell; $i++) {
$worksheet[$i][$newCol] = "";
foreach (array_keys($valArray) as $key) {
$worksheet[$i][$newCol] .= $valArray[$key] . $i;
}
if ($finalVal != NULL) {
$worksheet[$i][$newCol] .= $finalVal;
}
}
return $worksheet;
}
It's not SUMPRODUCT() that's causing the problem, it's the fact that PHPExcel doesn't support column/row ranges fully, so it's a column range like I:I or M:M or C:C that's causing the problem.
If you can change this to an actual cell range (e.g. I1:I2048), then it shouldn't be an issue.
And (for future reference) SUMIFS() is implemented in the latest code in the develop branch on github
i just want to know what this formula means .need help. please elaborate with if else statements.
=(IF(D11<=49.69,8.2404,IF(D11<50,((50-D11)*100*0.2084)+1.78, IF(D11>50.04, 0, ((50.05-D11)*100*0.356)))))
The syntax of the IF function in Excel is =IF(condition,value1,value2) where condition is something that evaluates to either TRUE or FALSE. value1 and value2 can be anything valid for insertion into an Excel cell: number, text or a formula. In the question, value2 is a formula which just happens to be another IF function and which also happens to contain further IF's in its arguments.
You can think of an IF in programming terms as
`If Condition Then Value1 Else Value2 End If'
The Help system in Excel is usually quite useful and a lot quicker than posting here and waiting for replies.
this is the logic:
If (D11<=49.69) Then
8.2404
Else
If (D11<50) Then
((50-D11)*100*0.2084)+1.78
Else
If (D11>50.04) Then
0
Else
((50.05-D11)*100*0.356)
End if
End If
End if
translated in php as:
if ($D11 <= 49.69) {
$x = 8.2404;
} elseif ($D11 < 50) {
$x = ((50-$D11)*100*0.2084)+1.78;
} elseif ($D11>50.04) {
$x = 0;
} else {
$x = ((50.05-$D11)*100*0.356)
}
I am looking for a solution to search for certain strings in a Google Sheet and, when found, replace them with another string from a list in another sheet.
For better understanding, I prepared a Sheet for you:
https://docs.google.com/a/vicampo.de/spreadsheets/d/1mETtAY72K6ST-hg1qOU9651265nGq0qvcgvzMRqHDO8/edit?usp=sharing
So here's the exact task I want to achieve:
In every single cell in column A of sheet "Text", look for the strings given in column A in sheet "List" and, when found, replace it with the corresponding string in column B of the sheet "List".
See my Example: Look in cell A1 for the string "Lorem" and replace it with "Xlorem", then look for the string "Ipsum" and replace it with "Xipsum", then look for the string "amet" and replace it with "Xamet" then move on to cell B1 and start again looking for the strings...
I have tried different functions and managed to do this with a function for one cell. But how to do it in a loop?
Thanks everyone who is interested in helping out with this problem!
Although there must be 'nicer' solutions, a quick solution (as long is the number of cells with the words you want replaced is not too long), would be:
=ArrayFormula(regexreplace(regexreplace(regexreplace(A1:A; List!A1; List!B1); List!A2; List!B2); List!A3; List!B3))
Probably the best for you, in this case, should be creating a new function to your Google Spreadsheet. It tends to be, in the general case, more simple, clear and powerfull than that kind of complex formulas that should do the same.
In this particular case, I have the same problem, so you can use the same function:
Click on "Tools" menu, then click on the "Script Editor" option. Into the script editor, erase the draft and paste this function:
function preg_quote( str ) {
// http://kevin.vanzonneveld.net
// + original by: booeyOH
// + improved by: Ates Goral (http://magnetiq.com)
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Onno Marsman
// * example 1: preg_quote("$40");
// * returns 1: '\$40'
// * example 2: preg_quote("*RRRING* Hello?");
// * returns 2: '\*RRRING\* Hello\?'
// * example 3: preg_quote("\\.+*?[^]$(){}=!<>|:");
// * returns 3: '\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:'
return (str+'').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1");
}
function ARRAYREPLACE(input,fromList,toList,caseSensitive){
/* default behavior it is not case sensitive */
if( caseSensitive === undefined ){
caseSensitive = false;
}
/* if the from list it is not a list, become a list */
if( typeof fromList != "object" ) {
fromList = [ fromList ];
}
/* if the to list it is not a list, become a list */
if( typeof toList != "object" ) {
toList = [ toList ];
}
/* force the input be a string */
var result = input.toString();
/* iterates using the max size */
var bigger = Math.max( fromList.length, toList.length) ;
/* defines the words separators */
var arrWordSeparator = [ ".", ",", ";", " " ];
/* interate into the lists */
for(var i = 0; i < bigger; i++ ) {
/* get the word that should be replaced */
var fromValue = fromList[ ( i % ( fromList.length ) ) ]
/* get the new word that should replace */
var toValue = toList[ ( i % ( toList.length ) ) ]
/* do not replace undefined */
if ( fromValue === undefined ) {
continue;
}
if ( toValue == undefined ) {
toValue = "";
}
/* apply case sensitive rule */
var caseRule = "g";
if( !caseSensitive ) {
/* make the regex case insensitive */
caseRule = "gi";
}
/* for each end word char, make the replacement and update the result */
for ( var j = 0; j < arrWordSeparator.length; j++ ) {
/* from value being the first word of the string */
result = result.replace( new RegExp( "^(" + preg_quote( fromValue + arrWordSeparator[ j ] ) + ")" , caseRule ), toValue + arrWordSeparator[ j ] );
/* from value being the last word of the string */
result = result.replace( new RegExp( "(" + preg_quote( arrWordSeparator[ j ] + fromValue ) + ")$" , caseRule ), arrWordSeparator[ j ] + toValue );
/* from value in the middle of the string between two word separators */
for ( var k = 0; k < arrWordSeparator.length; k++ ) {
result = result.replace(
new RegExp(
"(" + preg_quote( arrWordSeparator[ j ] + fromValue + arrWordSeparator[ k ] ) + ")" ,
caseRule
),
/* need to keep the same word separators */
arrWordSeparator[ j ] + toValue + arrWordSeparator[ k ]
);
}
}
/* from value it is the only thing in the string */
result = result.replace( new RegExp( "^(" + preg_quote( fromValue ) + ")$" , caseRule ), toValue );
}
/* return the new result */
return result;
}
Just save your script and the new function it will be available to you. Now, you have the function that replaces all the first values list by the second value list.
=ARRAYREPLACE(C2;A1:A4;B1:B4)
for example, takes the C2 text and replaces all the elements found in the A1:A4 list by the equivalent into the B1:B4 list.
Copy Sample File With Explanation
Problem
The challenge is:
Find & Replace multiple values in the input of multiple cells.
ArrayFormula's
Solutions which I account as Array-Solution must be:
based on open ranges
no need to drag the formula down
no need to modify the formula when new items in lists appear
These tests must be passed:
Is ArrayFormula
User can set Case Sensitivity
Replaces Emojis
Replaces Special Chars $\[]. etc.
CrashTest. Works for 10K rows of data
CrashTest. Works for 2K replacements
Script
I recommend using the not-regex-based script in this case. This algorithm finds and replaces text by chars:
Usage
Use as a regular formula from sheet:
=substitutes(A12:A;List!A1:B)
Code
Save this code to use the formula above:
/**
* Substitutes in every entry in array
* Text from prefilled array
*
* #param {array} input The array of strings.
* #param {array} subTable The array of string pairs: search texts / replace texts.
* #param {boolean} caseSensitive [optional=false]
* TRUE to match Apple and apple as different words
* #return The input with all replacement made
* #customfunction
*/
function substitutes(input, subTable,caseSensitive) {
// default behavior it is not case sensitive
caseSensitive = caseSensitive || false;
// if the input is not a list, become a list */
if( typeof input != "object" ) {
input = [ input ];
}
var res = [], text;
for (var i = 0; i < input.length; i++) {
// force each array element in the input be a string
text = input[i].toString();
for (var ii = 0; ii < subTable.length; ii++) {
text = replaceAll_(
text,
subTable[ii][0],
subTable[ii][1],
caseSensitive);
}
res.push(text);
}
return res;
}
/***
* JavaScript Non-regex Replace
*
* Original code sourse:
* https://stackoverflow.com/a/56989647/5372400
*/
function replaceAll_(str, find, newToken, caseSensitive) {
var i = -1;
// sanity check & defaults
if (!str) {
// Instead of throwing, act as
// COALESCE if find == null/empty and str == null
if ((str == null) && (find == null))
return newToken;
return str;
}
if (!find || find === ''){ return str; }
if (find === newToken) { return str; }
caseSensitive = caseSensitive || false;
find = !caseSensitive ? find.toLowerCase() : find;
// search process, search by char
while ((
i = (!caseSensitive ? str.toLowerCase() : str).indexOf(
find, i >= 0 ? i + newToken.length : 0
)) !== -1
) {
str = str.substring(0, i) +
newToken +
str.substring(i + find.length);
}
return str;
}
Monster Formula
I've used the RegEx algorithm to solve it with native functions. This method is not recommended as it slows down your Worksheet.
The formula is:
=INDEX(SUBSTITUTE(REGEXREPLACE(TRANSPOSE(QUERY(TRANSPOSE(IFERROR(SPLIT(SUBSTITUTE(TRANSPOSE(QUERY(TRANSPOSE(IFERROR(VLOOKUP(SPLIT(REGEXREPLACE(A12:A;SUBSTITUTE(REGEXREPLACE(REGEXREPLACE(A12:A;"(?i)"&SUBSTITUTE(SUBSTITUTE(QUERY(FILTER(REGEXREPLACE(List!A1:A;"(\\|\+|\*|\?|\[|\^|\]|\$|\(|\)|\{|\}|\=|\!|\<|\>|\||\:|\-)";"\\$1")&"𑇦";List!A1:A<>"");;2^99);"𑇦 ";"|");"𑇦";"");"𑇡");"(\\|\+|\*|\?|\[|\^|\]|\$|\(|\)|\{|\}|\=|\!|\<|\>|\||\:|\-)";"\\$1");"𑇡";"(.*)");INDEX(REGEXREPLACE(TRIM(TRANSPOSE(QUERY(TRANSPOSE(IF(SEQUENCE(COUNTA(INDEX(LEN(REGEXREPLACE(REGEXREPLACE(A12:A;"(?i)"&SUBSTITUTE(SUBSTITUTE(QUERY(FILTER(REGEXREPLACE(List!A1:A;"(\\|\+|\*|\?|\[|\^|\]|\$|\(|\)|\{|\}|\=|\!|\<|\>|\||\:|\-)";"\\$1")&"𑇦";List!A1:A<>"");;2^99);"𑇦 ";"|");"𑇦";"");"𑇡");"[^𑇡]";""))/2));MAX(INDEX(LEN(REGEXREPLACE(REGEXREPLACE(A12:A;"(?i)"&SUBSTITUTE(SUBSTITUTE(QUERY(FILTER(REGEXREPLACE(List!A1:A;"(\\|\+|\*|\?|\[|\^|\]|\$|\(|\)|\{|\}|\=|\!|\<|\>|\||\:|\-)";"\\$1")&"𑇦";List!A1:A<>"");;2^99);"𑇦 ";"|");"𑇦";"");"𑇡");"[^𑇡]";""))/2)))-(SEQUENCE(COUNTA(INDEX(LEN(REGEXREPLACE(REGEXREPLACE(A12:A;"(?i)"&SUBSTITUTE(SUBSTITUTE(QUERY(FILTER(REGEXREPLACE(List!A1:A;"(\\|\+|\*|\?|\[|\^|\]|\$|\(|\)|\{|\}|\=|\!|\<|\>|\||\:|\-)";"\\$1")&"𑇦";List!A1:A<>"");;2^99);"𑇦 ";"|");"𑇦";"");"𑇡");"[^𑇡]";""))/2)))-1)*MAX(INDEX(LEN(REGEXREPLACE(REGEXREPLACE(A12:A;"(?i)"&SUBSTITUTE(SUBSTITUTE(QUERY(FILTER(REGEXREPLACE(List!A1:A;"(\\|\+|\*|\?|\[|\^|\]|\$|\(|\)|\{|\}|\=|\!|\<|\>|\||\:|\-)";"\\$1")&"𑇦";List!A1:A<>"");;2^99);"𑇦 ";"|");"𑇦";"");"𑇡");"[^𑇡]";""))/2))<=INDEX(LEN(REGEXREPLACE(REGEXREPLACE(A12:A;"(?i)"&SUBSTITUTE(SUBSTITUTE(QUERY(FILTER(REGEXREPLACE(List!A1:A;"(\\|\+|\*|\?|\[|\^|\]|\$|\(|\)|\{|\}|\=|\!|\<|\>|\||\:|\-)";"\\$1")&"𑇦";List!A1:A<>"");;2^99);"𑇦 ";"|");"𑇦";"");"𑇡");"[^𑇡]";""))/2);"𑇣"&SEQUENCE(COUNTA(INDEX(LEN(REGEXREPLACE(REGEXREPLACE(A12:A;"(?i)"&SUBSTITUTE(SUBSTITUTE(QUERY(FILTER(REGEXREPLACE(List!A1:A;"(\\|\+|\*|\?|\[|\^|\]|\$|\(|\)|\{|\}|\=|\!|\<|\>|\||\:|\-)";"\\$1")&"𑇦";List!A1:A<>"");;2^99);"𑇦 ";"|");"𑇦";"");"𑇡");"[^𑇡]";""))/2));MAX(INDEX(LEN(REGEXREPLACE(REGEXREPLACE(A12:A;"(?i)"&SUBSTITUTE(SUBSTITUTE(QUERY(FILTER(REGEXREPLACE(List!A1:A;"(\\|\+|\*|\?|\[|\^|\]|\$|\(|\)|\{|\}|\=|\!|\<|\>|\||\:|\-)";"\\$1")&"𑇦";List!A1:A<>"");;2^99);"𑇦 ";"|");"𑇦";"");"𑇡");"[^𑇡]";""))/2)))-(SEQUENCE(COUNTA(INDEX(LEN(REGEXREPLACE(REGEXREPLACE(A12:A;"(?i)"&SUBSTITUTE(SUBSTITUTE(QUERY(FILTER(REGEXREPLACE(List!A1:A;"(\\|\+|\*|\?|\[|\^|\]|\$|\(|\)|\{|\}|\=|\!|\<|\>|\||\:|\-)";"\\$1")&"𑇦";List!A1:A<>"");;2^99);"𑇦 ";"|");"𑇦";"");"𑇡");"[^𑇡]";""))/2)))-1)*MAX(INDEX(LEN(REGEXREPLACE(REGEXREPLACE(A12:A;"(?i)"&SUBSTITUTE(SUBSTITUTE(QUERY(FILTER(REGEXREPLACE(List!A1:A;"(\\|\+|\*|\?|\[|\^|\]|\$|\(|\)|\{|\}|\=|\!|\<|\>|\||\:|\-)";"\\$1")&"𑇦";List!A1:A<>"");;2^99);"𑇦 ";"|");"𑇦";"");"𑇡");"[^𑇡]";""))/2))&"𑇤";));;2^99)));" ?𑇣";"$")));"𑇤");{List!A1:A\List!B1:B};2;)&"𑇩"));;2^99));"𑇩 ";"𑇩")&"𝅘";"𑇩")&SPLIT(REGEXREPLACE(A12:A;"(?i)"&SUBSTITUTE(SUBSTITUTE(QUERY(FILTER(REGEXREPLACE(List!A1:A;"(\\|\+|\*|\?|\[|\^|\]|\$|\(|\)|\{|\}|\=|\!|\<|\>|\||\:|\-)";"\\$1")&"𑇦";List!A1:A<>"");;2^99);"𑇦 ";"|");"𑇦";"");"𑇡")&"𝅘";"𑇡")))&"𝅗";;2^99));"𝅗 *";"");"𝅘";""))
Other Solutions
Nested formulas
Nested SUBSTITUTE or REGEXREPLACE formulas as was noted in other answers.
Formulas you need to drag down for the result
Here's a sample formula. Basic logic - split the text into parts → modify parts individually → to join the new result.
This formula must be copied down:
=JOIN(" ";
ArrayFormula(
IFERROR(VLOOKUP(TRANSPOSE(SPLIT(A1;" "));List!A:B;2;0);TRANSPOSE(SPLIT(A1;" ")))))
An improvement on JPV's answer, which is orders of magnitude faster and works with arbitrary query and replacement strings:
=ArrayFormula(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1:A, List!A1, List!B1), List!A2, List!B2), List!A3, List!B3))
Using this format, a 15,000 cell spreadsheet with an 85-length replacement list will update in just a few seconds. Simply assemble the formula string using your scripting language of choice and you're good to go!
With new Labmda and Friends:
=LAMBDA(data,re,with,BYROW(data,LAMBDA(r,if(r="","",REDUCE(r,SEQUENCE(counta(re)),LAMBDA(ini,v,REGEXREPLACE(ini,INDEX(re,v),INDEX(with,v))))))))(C5:C6,E5:E7,F5:F7)
=> Named function
=SUBSTITUTES_RE(list0,list_re,list_with)
↑ This will substitute using regular expressions
substututes
Definition is the same, but REGEXREPLACE is replaced with SUBSTITUTE
Other examples here:
https://docs.google.com/spreadsheets/d/1IMymPZlibT6DX4yzDX4OXj2XBZ48zEl6vBUzIHJIzVE/edit#gid=0
Here is a bit simpler of a script than Thiago Mata's. I modified the script from https://webapps.stackexchange.com/a/46895 to support either single cell or range input
function MSUBSTITUTE(input, subTable)
{
var searchArray = [], subArray = [], outputArray = [];
for (var i = 0, length = subTable.length; i < length; i++)
{
if (subTable[i][0])
{
searchArray.push(subTable[i][0]);
subArray.push(subTable[i][1]);
}
}
var re = new RegExp(searchArray.join('|'), 'g');
/* Check if we got just a single string */
if (typeof( input ) == "string")
{
outputArray.push(input.replace(re, function (match) {return subArray[searchArray.indexOf(match)];}));
}
else /* we got an array of strings */
{
for (var i = 0; i < input.length; i++)
{
/* force each array element in the input be a string */
var text = input[i].toString();
outputArray.push(text.replace(re, function (match) {return subArray[searchArray.indexOf(match)];}))
}
}
return outputArray;
}
I've found a simple way to do this with "ARRAYFORMULA"
You must have one list with the text to find and in a contiguos column, the list you want to replace de data, for example:
#
D
E
1
ToFind
ToReplace
2
Avoc4do
Avocado
3
Tomat3
Tomate
4
On1on
Onion
5
Sug4r
Sugar
then use this formula
=ARRAYFORMULA(FIND(A1:A1000,D1:D5,E1:E5))
A1:A1000 is the original column where you have multiple rows with the word "Avoc4do, Tomat3, On1on, Sugar", ArrayFormula works with a matrix where others formulas can't (formula FIND can't work finding in a matrix, so we use ArrayFormula)
Then you will have a colum with the 1000 rows but now with the "ToReplace" text in order, so now cut and copy in the column A, that's it.
Got it
Lorem ipsum dolor sit xamet Lorem ipsum
= textjoin("";true;ARRAYFORMULA(ifna(vlookup(REGEXEXTRACT(A1;"("®EXREPLACE(A1;"("&(textJOIN("|";true;lookuprange))&")";")($1)(")&")");lookuprange;2;false);REGEXEXTRACT(A1;"("®EXREPLACE(A1;"("&(textJOIN("|";true;lookuprange))&")";")($1)(")&")"))))
Xlorem ipsum dolor sit Xamet Xlorem ipsum