Writing strings into excel using Matlab? - excel

I am writing a cell array of string into Excel from Matlab. I have a cell array data{} that I am trying to write into Matlab. It should writting three large lengths of strings to excel since the strcmp passes 3 times. Currently it is only writing the last set of strings into excel. data = { {1x25} {1x35} {1x20} } looks like this. Also I would like to be able to write the data into three cells instead of getting copyied into as many cells as there are lines in the element of the cell array. Is this possible to do with Matlab to excel?
done = {}
for i = 1:3
q = strcmp(x_gene_ID{i},locus_tags{i});
if q ==1
done{end+1} = data{i};
disp(done);
end
end
w = xlswrite('data.xlsx',done','E2:E400');
Ok that helps I am aware the cell array's are larger than 3 cell range. I am trying to get the Nx1 cell array to fit into one cell in Excel because It needs to correspond to information in an adjacent cell. Is this at all possible to do?
A B C D E
w Rv0146 na Rv0039c (i want the cell array1 to go here)
s Rv0156 na Rv0029c (i want the cell array2 to go here)
s Rv0156 na Rv0029c (i want the cell array2 to go here)
Here is what I am looking to do in excel

UPDATED ANSWER:
If I understand correctly, it appears that your variable data is a cell array where each cell contains a 1-by-N (or perhaps N-by-1) cell array of strings. If you want to try and fit each of these cell arrays of strings into one cell of a spreadsheet, you are going to need to format each into a single long string first.
Here's an example of how you could format the cell arrays of strings by concatenating them together with a newline between them:
data = {{'hello' 'hi' 'hey'} ... %# Sample cell array of 1-by-N
{'world' 'earth' 'everyone'} ... %# cell arrays of strings
{'blah' 'blah'}};
data = cellfun(#(x) {strcat(x,{char(10)})},data); %# Add newline characters
%# to the string ends
data = cellfun(#(x) {deblank([x{:}])},data); %# Concatenate the inner cells and
%# remove the trailing newlines
Now that each cell array of strings is just a single long string, each string can be written to a cell of an Excel spreadsheet as follows:
xlswrite('data.xls',data(:),'Sheet1','E2'); %# Write the data to cells E2 to E4
And here's what the resulting spreadsheet looks like:
If you use a space ' ' instead of a newline character, here's what the spreadsheet looks like (after adjusting the row and column widths):
Functions used in the above code: CELLFUN, STRCAT, CHAR, DEBLANK, XLSWRITE.

Related

Check id every value in ";" separated string exists on a LOV list using just Excel formulas

In a cell I have a multi value separated by semicolon like this:
Red;Blue;Green
I need to compare if each of those values exist on a list:
Black
Orange
Green
Blue
Red
I think it should be an array formula, but I have no idea how to set it.
Is it even possible?
Regards
Michał
You've not mentioned what output you are looking for. Below are the two possible solution.
1. If you are looking for the count of words in a cell from the list use following formula:
=SUMPRODUCT(ISNUMBER(FIND($E$2:$E$6,$A2))*1)
2. If you want words in the cell that are in the list to be displayed in separate columns, use the following array formula
=IFERROR(INDEX($J$2:$J$6,SMALL(IF(ISNUMBER(FIND($J$2:$J$6,$A2)),ROW($J$2:$J$6)-ROW($J$1)),COLUMNS($A1:A1))),"")
Drag/copy above formula across and down as required.
Being an array formula you'll have to commit this formula by pressing Ctrl+Shift+Enter.
You can write this UDF and use it as a formula. Wasn't sure what output is required. This UDF gives number of items that match in the list.
Parameters:
myValue - the cell that contains multi value separated by semicolon
listRange - Range that has the list to check against. Should be a single column list
Function checkList(myValue As Range, listRange As Range) As Integer
Dim t As Variant
t = Split(myValue.Value, ";")
Dim c As Integer
c = 0
For i = LBound(t) To UBound(t)
For j = 1 To listRange.Rows.Count
If (t(i) = listRange(j, 1)) Then
c = c + 1
End If
Next j
Next i
checkList = c
End Function
Since you want to do this only with excel formulas, the input string has to be split to multiple cells before comparing it with the list.
If your input string is in A1, use the below formula and drag it right to split them based on the delimiter ;.
=TRIM(MID(SUBSTITUTE($A1,";",REPT(" ",999)),1+((COLUMN(A1)-1)*999),999))
Assuming your list is in column G, use the below formula which counts the strings Red, Blue and Green in your list and returns Found or Not found.
in C2,
=IF(COUNTIF($G:$G,C1),"Found","Not found")
Hope this helps.

Excel: extract only substrings beginning with a certain character

I have a column of cells containing a variable amount of text up to 140 characters in length. What I would like to do is write a function that will parse these strings for only words beginning with "#" and organize them in a single adjacent cell separated by spaces.
These substrings vary in length and in their position within the string. And there might be more than one substring beginning with "#" in the cell to pull.
I have tried it in many different ways which have been unsuccessful. Thanks in advance for your advice!
Here is a way that seems to work, but is probably not the "correct" way:
The objective was to parse column C, containing tweets, for all the "mentions" (strings beginning with #) and put them in an adjacent cell in column D.
I took all the content from column C and pasted it into a new sheet. Then I did text-to-column so that the tweet was put into cells word by word. On these cells I used the function (dragged out) =IF(ISNUMBER(FIND("#",B3)),CONCATENATE(B3," "),"") in order to separate the twitter handles only into columns below. I think there needs to be a space added in case there are multiple handles to join.
Then I used another nested CONCATENATE function =CONCATENATE(IF(B34="","",B34),IF(B35="","",B35)...,IF(B65="","",B65) to put the handles, now followed by spaces, together in a single cell. It had to be written this way as a workaround for the #VALUE error for the CONCATENATE function in blank cells.
Then I selected the whole row, copied and transposed it into a column. Then selected the column, pasted values only into my original sheet in column D. The handles all line up with the corresponding tweet.
I would love to learn how to do this in the proper way.
Dim regEx As Object
Dim strPattern As String: strPattern = "^#"
Set regEx = CreateObject("VBScript.RegExp")
regEx.Pattern = strPattern
If regEx.Test(valueOfCellToCheck) Then
' do your logic here
Else
' skip cell
End If

Writing a char matrix to Excel using xlswrite

Could someone assist in writing a char matrix to Excel? The following is a <17x6 char>
A =
SPK01a
SPK03a
SPK03b
SPK05a
SPK07a
SPK07b
SPK07c
SPK09a
SPK11a
SPK15a
SPK17a
SPK19a
SPK21a
SPK23a
SPK25a
SPK27a
SPK29a
I was trying to do xlswrite(filename, {A}) but receive the error:
Error using xlswrite (line 220)
ActiveX - Element of a cell array cannot be a character matrix.
I need the strings to be in cells, so in this case, in the first column in Excel, in 17 separate cells.
You can use cellstr to make a properly shaped cell array:
xlswrite(fileName,cellstr(A))
cellstr provides a quick way to place each row of a character array into a separate cell, and it will remove trailing spaces at the end of each row.
Use mat2cell to convert your matrix of characters into a cell array and use that to write into an excel file -
xlswrite(xls_filename,mat2cell(A,ones(1,size(A,1))))
This will write everything to the first column of the excel sheet, but in different rows.

How to merge rows in a column into one cell in excel?

E.g
A1:I
A2:am
A3:a
A4:boy
I want to merge them all to a single cell "Iamaboy"
This example shows 4 cells merge into 1 cell however I have many cells (more than 100), I can't type them one by one using A1 & A2 & A3 & A4 what can I do?
If you prefer to do this without VBA, you can try the following:
Have your data in cells A1:A999 (or such)
Set cell B1 to "=A1"
Set cell B2 to "=B1&A2"
Copy cell B2 all the way down to B999 (e.g. by copying B2, selecting cells B3:B99 and pasting)
Cell B999 will now contain the concatenated text string you are looking for.
I present to you my ConcatenateRange VBA function (thanks Jean for the naming advice!) . It will take a range of cells (any dimension, any direction, etc.) and merge them together into a single string. As an optional third parameter, you can add a seperator (like a space, or commas sererated).
In this case, you'd write this to use it:
=ConcatenateRange(A1:A4)
Function ConcatenateRange(ByVal cell_range As range, _
Optional ByVal separator As String) As String
Dim newString As String
Dim cell As Variant
For Each cell in cell_range
If Len(cell) <> 0 Then
newString = newString & (separator & cell)
End if
Next
If Len(newString) <> 0 Then
newString = Right$(newString, (Len(newString) - Len(separator)))
End If
ConcatenateRange = newString
End Function
Inside CONCATENATE you can use TRANSPOSE if you expand it (F9) then remove the surrounding {}brackets like this recommends
=CONCATENATE(TRANSPOSE(B2:B19))
Becomes
=CONCATENATE("Oh ","combining ", "a " ...)
You may need to add your own separator on the end, say create a column C and transpose that column.
=B1&" "
=B2&" "
=B3&" "
In simple cases you can use next method which doesn`t require you to create a function or to copy code to several cells:
In any cell write next code
=Transpose(A1:A9)
Where A1:A9 are cells you would like to merge.
Without leaving the cell press F9
After that, the cell will contain the string:
={A1,A2,A3,A4,A5,A6,A7,A8,A9}
Source: http://www.get-digital-help.com/2011/02/09/concatenate-a-cell-range-without-vba-in-excel/
Update: One part can be ambiguous. Without leaving the cell means having your cell in editor mode. Alternatevly you can press F9 while are in cell editor panel (normaly it can be found above the spreadsheet)
Use VBA's already existing Join function. VBA functions aren't exposed in Excel, so I wrap Join in a user-defined function that exposes its functionality. The simplest form is:
Function JoinXL(arr As Variant, Optional delimiter As String = " ")
'arr must be a one-dimensional array.
JoinXL = Join(arr, delimiter)
End Function
Example usage:
=JoinXL(TRANSPOSE(A1:A4)," ")
entered as an array formula (using Ctrl-Shift-Enter).
Now, JoinXL accepts only one-dimensional arrays as input. In Excel, ranges return two-dimensional arrays. In the above example, TRANSPOSE converts the 4×1 two-dimensional array into a 4-element one-dimensional array (this is the documented behaviour of TRANSPOSE when it is fed with a single-column two-dimensional array).
For a horizontal range, you would have to do a double TRANSPOSE:
=JoinXL(TRANSPOSE(TRANSPOSE(A1:D1)))
The inner TRANSPOSE converts the 1×4 two-dimensional array into a 4×1 two-dimensional array, which the outer TRANSPOSE then converts into the expected 4-element one-dimensional array.
This usage of TRANSPOSE is a well-known way of converting 2D arrays into 1D arrays in Excel, but it looks terrible. A more elegant solution would be to hide this away in the JoinXL VBA function.
For those who have Excel 2016 (and I suppose next versions), there is now directly the CONCAT function, which will replace the CONCATENATE function.
So the correct way to do it in Excel 2016 is :
=CONCAT(A1:A4)
which will produce :
Iamaboy
For users of olders versions of Excel, the other answers are relevant.
For Excel 2011 on Mac it's different. I did it as a three step process.
Create a column of values in column A.
In column B, to the right of the first cell, create a rule that uses the concatenate function on the column value and ",". For example, assuming A1 is the first row, the formula for B1 is =B1. For the next row to row N, the formula is =Concatenate(",",A2). You end up with:
QA
,Sekuli
,Testing
,Applitools
,Visual Testing
,Test Automation
,Selenium
In column C create a formula that concatenates all previous values. Because it is additive you will get all at the end. The formula for cell C1 is =B1. For all other rows to N, the formula is =Concatenate(C1,B2). And you get:
QA,Sekuli
QA,Sekuli,Testing
QA,Sekuli,Testing,Applitools
QA,Sekuli,Testing,Applitools,Visual Testing
QA,Sekuli,Testing,Applitools,Visual Testing,Test Automation
QA,Sekuli,Testing,Applitools,Visual Testing,Test Automation,Selenium
The last cell of the list will be what you want. This is compatible with Excel on Windows or Mac.
I use the CONCATENATE method to take the values of a column and wrap quotes around them with columns in between in order to quickly populate the WHERE IN () clause of a SQL statement.
I always just type =CONCATENATE("'",B2,"'",",") and then select that and drag it down, which creates =CONCATENATE("'",B3,"'",","), =CONCATENATE("'",B4,"'",","), etc. then highlight that whole column, copy paste to a plain text editor and paste back if needed, thus stripping the row separation. It works, but again, just as a one time deal, this is not a good solution for someone who needs this all the time.
I know this is really a really old question, but I was trying to do the same thing and I stumbled upon a new formula in excel called "TEXTJOIN".
For the question, the following formula solves the problem
=TEXTJOIN("",TRUE,(a1:a4))
The signature of "TEXTJOIN" is explained as TEXTJOIN(delimiter,ignore_empty,text1,[text2],[text3],...)
I needed a general purpose Concatenate With Separator (since I don't have TEXTJOIN) so I wrote this:
Public Function ConcatWS(separator As String, ParamArray cell_range()) As String
'---concatenate with seperator
For n = LBound(cell_range) To UBound(cell_range)
For Each cell In cell_range(n)
If Len(cell) <> 0 Then
ConcatWS = ConcatWS & IIf(ConcatWS <> "", separator, "") & cell
End If
Next
Next n
End Function
Which allows us to go crazy with flexibility in including cell ranges:
=ConcatWS(" ", Fields, E1:G2, L6:M9, O6)
NOTE: "Fields" is a Named Range and the separator may be blank

Writing a cell array of strings to Excel from Matlab?

I want to write the names of genes into excel but when I run this code matlab doesnt write anything into excel. The cells I want filled are left blank. I cant seem to figure out what I am missing in my code. names is a cell array of string names.
function nameWriter()
x = importdata('mitominerratmitochondrialoutermembraneproteins');
names = {};
n = length(x.textdata);
counter = 0;
for i = 1:n
if strncmp(x.textdata(i),'>', 1) ==1
names{end+1} = x.textdata(i);
counter = counter +1;
end
end
xlswrite('aacount2.xls', names, 'B1:CB1');
end
I believe the likely source of your error is that you are not taking into account that x.textdata is going to be a cell array of strings (as described in the table in the IMPORTDATA documentation for the output argument A). When you assign data to names like so:
names{end+1} = x.textdata(i);
You are actually placing a cell array inside another cell array, and XLSWRITE apparently can't handle nested cell arrays (i.e. it outputs blank fields for cell elements of the input that contain cell arrays). You should instead use curly braces, not parentheses, to access the cell contents of x.textdata, like so:
names{end+1} = x.textdata{i};

Resources