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

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

Related

Using fscanf in MATLAB to read an unknown number of columns

I want to use fscanf for reading a text file containing 4 rows with an unknown number of columns. The newline is represented by two consecutive spaces.
It was suggested that I pass : as the sizeA parameter but it doesn't work.
How can I read in my data?
update: The file format is
String1 String2 String3
10 20 30
a b c
1 2 3
I have to fill 4 arrays, one for each row.
See if this will work for your application.
fid1=fopen('test.txt');
i=1;
check=0;
while check~=1
str=fscanf(fid1,'%s',1);
if strcmp(str,'')~=1;
string(i)={str};
end
i=i+1;
check=strcmp(str,'');
end
fclose(fid1);
X=reshape(string,[],4);
ar1=X(:,1)
ar2=X(:,2)
ar3=X(:,3)
ar4=X(:,4)
Once you have 'ar1','ar2','ar3','ar4' you can parse them however you want.
I have found a solution, i don't know if it is the only one but it works fine:
A=fscanf(fid,'%[^\n] *\n')
B=sscanf(A,'%c ')
Z=fscanf(fid,'%[^\n] *\n')
C=sscanf(Z,'%d')
....
You could use
rawText = getl(fid);
lines = regexp(thisLine,' ','split);
tokens = {};
for ix = 1:numel(lines)
tokens{end+1} = regexp(lines{ix},' ','split'};
end
This will give you a cell array of strings having the row and column shape or your original data.
To read an arbitrary line of text then break it up according the the formating information you have available. My example uses a single space character.
This uses regular expressions to define the separator. Regular expressions powerful but too complex to describe here. See the MATLAB help for regexp and regular expressions.

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.

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

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.

Return a String value from my popup menu in MatLab

I am developing a simple GUI with MATLAB (guide) with a pop up menu in it. In order to establish a connection through a serial port.
function sendLog_OpeningFcn(hObject, eventdata, handles, varargin)
set(handles.popupmenuSerialPort,'String', {'''COM1''','''COM2''','''COM3''','''COM4'''});
...
I would like to get the selected value in this way:
serialPortList = get(handles.popupmenuSerialPort,'String');
serialPortValue = get(handles.popupmenuSerialPort,'Value');
serialPort = serialPortList(serialPortValue);
disp('serialPort ' + serialPortValue);
But I get an error message on disp function:
Undefined function 'plus' for input arguments of type 'cell'.
Invalid PORT specified.
How could I get the chosen value?
I hate to plow through 2 answers that are clearly not bad, but here the devil is in the details. Yes, you cannot concatenate strings in MATLAB with the + operator, but the first red flag in your question is that your error message indicates a cell as one of the arguments to +. Note that disp has not even thrown an error at this point, it was +. This leads me to believe that your code is actually disp('serialPort ' + serialPort); not disp('serialPort ' + serialPortValue); since serialPortList is a cell array. Was this a typo?
So, by indexing it like serialPort = serialPortList(serialPortValue); you get a single cell in serialPort, which would not work with proper string concatenation or disp. The correction here is to use the curly braces ({}).
Together with valid string concatenation,
>> serialPort = serialPortList{serialPortValue};
>> disp(['serialPort ' serialPort])
serialPort 'COM3'
The single quotes are in the string because of how you set the strings with set(handles.popupmenuSerialPort,'String',..., so if you want to strip that, you can use strrep(serialPort,'''','').
Note that you can also use fprintf if you are more comfortable with that style of string formatting.
You can't use '+' to combine strings in matlab.
you can do:
disp(['serialPort',num2str(serialPortValue)]);
Try array concatenation :
disp(['SerialPort : ' serialPortValue]);

Extracting strings from cells in MATLAB [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Using regexp to find a word
I'm working on an assignment for my CS course.
We're given a plain text file, which, in my case, contains a series of tweets.
What I need to do is create a script that will detect hashtags, and then save each hashtag into an cell array.
So far I know how to write a function that detects the '#' symbol...
strfind(textRead{i},'#');
where in a for loop where i=1:30 (that is, the number of cells of text). However, past that, I'm at a loss as to how I should write a script that will detect the '#' and return the text between that and the next ' ' (space) character.
Try this:
str = '#someHashtag other tweet text ignore #random';
regexp(str, '#[A-z]*', 'match')
I think you'll be able to find the rest out yourself :)
Here is basic skeleton. But make sure to use correct regexp to extract the values ;-)
Yes with the above Dorin's regexp and match you get one value at a time. You may add a token as per this example from mathworks.
Sample:
str = ['if <code>A </code> == x<sup>2 </sup>, ' ... '<em>disp(x) </em>']
str = if <code>A </code> == x<sup>2 </sup>, <em>disp(x) </em>
expr = '<(\w+).*?>.*?</\1>';
[tok mat] = regexp(str, expr, 'tokens', 'match');
tok{:}
ans = 'code'
ans = 'sup'
ans = 'em'
in above code you don't really need to loop and can process entire text bulk as one string , hopefully not hitting any string limit......
But if you want to loop, or if you need to loop, you use the following sample with Rody's regexp and match only.
fid = fopen('data.txt');
dataText = fgetl(fid);
while ~feof(fid)
ldata = textscan(dataText,'*%d#*');
X = (ldata, '#[A-z]*', 'match')
Cellarray = X{1}
end
Disp(X)
fclose(fid);