printing a vector of string in static text box with new lines - matlab

I have a bunch of classes that I am iterating through and collecting which classes the student is failing in. If the student fails , I collect the name of the class in a vector called retake.
retake =[Math History Science]
I have line breaks so when the classes print in the command window it shows as:
retake=
Math
History
Science.
However, I am trying display retake in a static text box in Gui Guide so it looks like the above. Instead, the static text box is showing as:
MathHistoryScience
set(handles.text13,'String', retake) % this is what I tried
can you please show me so it prints:
Math
History
Science

It looks to me like you need to add carriage returns.
Assuming you have a cell array with strings (rather than concatenated strings using [], which will give you a single long line), you can do it as follows:
retake = {'Math', 'History', 'Science'};
rString = '';
for ii = 1:numel(retake)-1
rString = [rString sprintf('%s\n', retake{ii}];
end
rString = [rString retake{end}];
Notice the use of '' to denote strings, {} to denote a cell array, '\n' as the end-of-line character, and [a b] to do simple string concatenation.

Related

Converting numbers into timestamps (inserting colons at specific places)

I'm using AutoHotkey for this as the code is the most understandable to me. So I have a document with numbers and text, for example like this
120344 text text text
234000 text text
and the desired output is
12:03:44 text text text
23:40:00 text text
I'm sure StrReplace can be used to insert the colons in, but I'm not sure how to specify the position of the colons or ask AHK to 'find' specific strings of 6 digit numbers. Before, I would have highlighted the text I want to apply StrReplace to and then press a hotkey, but I was wondering if there is a more efficient way to do this that doesn't need my interaction. Even just pointing to the relevant functions I would need to look into to do this would be helpful! Thanks so much, I'm still very new to programming.
hfontanez's answer was very helpful in figuring out that for this problem, I had to use a loop and substring function. I'm sure there are much less messy ways to write this code, but this is the final version of what worked for my purposes:
Loop, read, C:\[location of input file]
{
{ If A_LoopReadLine = ;
Continue ; this part is to ignore the blank lines in the file
}
{
one := A_LoopReadLine
x := SubStr(one, 1, 2)
y := SubStr(one, 3, 2)
z := SubStr(one, 5)
two := x . ":" . y . ":" . z
FileAppend, %two%`r`n, C:\[location of output file]
}
}
return
Assuming that the "timestamp" component is always 6 characters long and always at the beginning of the string, this solution should work just fine.
String test = "012345 test test test";
test = test.substring(0, 2) + ":" + test.substring(2, 4) + ":" + test.substring(4, test.length());
This outputs 01:23:45 test test test
Why? Because you are temporarily creating a String object that it's two characters long and then you insert the colon before taking the next pair. Lastly, you append the rest of the String and assign it to whichever String variable you want. Remember, the substring method doesn't modify the String object you are calling the method on. This method returns a "new" String object. Therefore, the variable test is unmodified until the assignment operation kicks in at the end.
Alternatively, you can use a StringBuilder and append each component like this:
StringBuilder sbuff = new StringBuilder();
sbuff.append(test.substring(0,2));
sbuff.append(":");
sbuff.append(test.substring(2,4));
sbuff.append(":");
sbuff.append(test.substring(4,test.length()));
test = sbuff.toString();
You could also use a "fancy" loop to do this, but I think for something this simple, looping is just overkill. Oh, I almost forgot, this should work with both of your test strings because after the last colon insert, the code takes the substring from index position 4 all the way to the end of the string indiscriminately.

Function to split string in matlab and return second number

I have a string and I need two characters to be returned.
I tried with strsplit but the delimiter must be a string and I don't have any delimiters in my string. Instead, I always want to get the second number in my string. The number is always 2 digits.
Example: 001a02.jpg I use the fileparts function to delete the extension of the image (jpg), so I get this string: 001a02
The expected return value is 02
Another example: 001A43a . Return values: 43
Another one: 002A12. Return values: 12
All the filenames are in a matrix 1002x1. Maybe I can use textscan but in the second example, it gives "43a" as a result.
(Just so this question doesn't remain unanswered, here's a possible approach: )
One way to go about this uses splitting with regular expressions (MATLAB's strsplit which you mentioned):
str = '001a02.jpg';
C = strsplit(str,'[a-zA-Z.]','DelimiterType','RegularExpression');
Results in:
C =
'001' '02' ''
In older versions of MATLAB, before strsplit was introduced, similar functionality was achieved using regexp(...,'split').
If you want to learn more about regular expressions (abbreviated as "regex" or "regexp"), there are many online resources (JGI..)
In your case, if you only need to take the 5th and 6th characters from the string you could use:
D = str(5:6);
... and if you want to convert those into numbers you could use:
E = str2double(str(5:6));
If your number is always at a certain position in the string, you can simply index this position.
In the examples you gave, the number is always the 5th and 6th characters in the string.
filename = '002A12';
num = str2num(filename(5:6));
Otherwise, if the formating is more complex, you may want to use a regular expression. There is a similar question matlab - extracting numbers from (odd) string. Modifying the code found there you can do the following
all_num = regexp(filename, '\d+', 'match'); %Find all numbers in the filename
num = str2num(all_num{2}) %Convert second number from str

Function to shuffle letters in words in matlab using randperm?? Changing from non-function format

I have the following to shuffle the letters in a word, but I need to change it into the form of a function that asks the user to input a word, and outputs the shuffled word.
How can I do this???
word = input('type a word to be scrambled: ', 's');
word(randperm(numel(word)))
The code you have to scramble the word is indeed correct. To do what you're asking, you really only have to make one change to the above code. Just place a function declaration in a .m file and call it something like scramble.m. Then do:
function word = scramble
word = input('type a word to be scrambled: ', 's');
word(randperm(numel(word)))
end
This should output the word as a string when you call the function. So save this file, then in the command prompt, type in:
>> word = scramble;
This should ask you for the word you want scrambled, scramble it and return the word. This word is stored in the variable word in the MATLAB workspace.
Some suggested reading for you: http://www.mathworks.com/help/matlab/ref/function.html
MathWorks is very good with their documentation and especially the syntax. Read the above link for further details on how you define a function and use it, but the gist of it is how I did it above.
The general format of a matlab function is
function output = MyFunctionName(input)
... code using 'input' goes here
end %
If you have multiple outputs, you place them inside an array, preferably separated by commas. If you have multiple inputs, you list them separated by commas:
function [out1, out2,...,outN] = MyFunctionName(input1, input2,...,inputN)
... code using the inputs goes here
end %
For your problem, you're not passing the word to the function so the call the function needs no input, BUT you need to input the word from inside the function. Here's one way to do it.
function word = ShuffleLetters
% Output: 'word' that is shuffled within function
% Input: none
word = input('type a word to be scrambled: ', 's');
word = word(randperm(numel(word)));
end
Here's a sample usage:
>> ShuffleLetters
type a word to be scrambled: bacon
ans =
bonca
Finally, inputs and outputs are optional. This m-function just prints 'Hi!'
function SayHi
disp('Hi!')
end

Loading files in a for loop in matlab

I am trying to load different file names contained in a matlab vector inside a for loop. I wrote the following:
fileNames = ['fileName1.mat', ..., 'fileName_n.mat'];
for i=1:n
load(fileNames(i))
...
end
However, it doesn't work because fileNames(i) returns the first letter of the filename only.
How can I give the full file name as argument to load (the size of the string of the filename can vary)
Use a cell instead of an array.
fileNames = {'fileName1.mat', ..., 'fileName_n.mat'};
Your code is in principle a string cat, giving you just one string (since strings are arrays of characters).
for i=1:n
load(fileNames{i})
...
end
Use { and } instead of parentheses.

Create an array of strings

Is it possibe to create an array of strings in MATLAB within a for loop?
For example,
for i=1:10
Names(i)='Sample Text';
end
I don't seem to be able to do it this way.
You need to use cell-arrays:
names = cell(10,1);
for i=1:10
names{i} = ['Sample Text ' num2str(i)];
end
You can create a character array that does this via a loop:
>> for i=1:10
Names(i,:)='Sample Text';
end
>> Names
Names =
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
However, this would be better implemented using REPMAT:
>> Names = repmat('Sample Text', 10, 1)
Names =
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Another option:
names = repmat({'Sample Text'}, 10, 1)
New features have been added to MATLAB recently:
String arrays were introduced in R2016b (as Budo and gnovice already mentioned):
String arrays store pieces of text and provide a set of functions for
working with text as data. You can index into, reshape, and
concatenate strings arrays just as you can with arrays of any other
type.
In addition, starting in R2017a, you can create a string using double quotes "".
Therefore if your MATLAB version is >= R2017a, the following will do:
for i = 1:3
Names(i) = "Sample Text";
end
Check the output:
>> Names
Names =
1×3 string array
"Sample Text" "Sample Text" "Sample Text"
No need to deal with cell arrays anymore.
Another solution to this old question is the new container string array, introduced in Matlab 2016b. From what I read in the official Matlab docs, this container resembles a cell-array and most of the array-related functions should work out of the box. For your case, new solution would be:
a=repmat('Some text', 10, 1);
This solution resembles a Rich C's solution applied to string array.
As already mentioned by Amro, the most concise way to do this is using cell arrays. However, Budo touched on the new string class introduced in version R2016b of MATLAB. Using this new object, you can very easily create an array of strings in a loop as follows:
for i = 1:10
Names(i) = string('Sample Text');
end
one of the simplest ways to create a string matrix is as follow :
x = [ {'first string'} {'Second parameter} {'Third text'} {'Fourth component'} ]