Accessing strings from a array of strings in GNU Octave - string

How to access the whole elements hello and ahoy in Octave? Only the first character in each string is being printed.
octave:1> s = ["hello";"ahoy"]
s =
hello
ahoy
octave:2> s(1)
ans = h
octave:3> s(2)
ans = a

Use cell arrays instead.
octave:1> s = { 'hello'; 'ahoy' };
octave:2> s{1}
ans = hello
octave:3> s{2}
ans = ahoy
See https://octave.org/doc/v5.2.0/Cell-Arrays.html#Cell-Arrays

Check the size and type of s to understand what's going on:
octave:5> size(s)
ans =
2 5
octave:6> class(s)
ans = char
It's a 2x5 matrix of characters. To index, use matrix indexing. For example getting the first row:
octave:7> s(1,:)
ans = hello

Related

Trying to convert each x'th character to Uppercase

So basically my homework consists of making a program that asks for a string and an integer 'x'.'x' is basically the step in this program. First it converts the whole string to lowercase and then each 'x'th' character of the string must be converted to uppercase. So if i input "Hello World" and my integer is 1. Output would be "hElLo wOrLd". Im new to python by the way.
This is what ive got right now and im basically stuck in a loop of trying a 100 things:
s = input('Input a string: ')
g = input('Input an integer: ')
s = s.lower() #converts the whole string ofc
s = list(s)
range1 = s[::g]
range1 = range1.upper()
print(s)
First, convert g to an int because input returns a str and you can't slice a list with a str, also, s[::g] (which should be s[g::g + 1]) is an independent sublist of s, and it has no reference to s, so assigning it to range1 and modifying it will not modify s, and one more note, s[::g] is a list, and you should call str.upper on its elements, not on it itself, you can use map for this:
s = list(input('Input a string: ').lower())
g = int(input('Input an integer: '))
s[g::g + 1] = map(str.upper, s[g::g + 1])
s = ''.join(s)
print(s)
Input:
Input a string: Hello World
Input an integer: 1
Output:
hElLo wOrLd

Matlab String Conversion to Array

I got a string array of the format
sLine =
{
[1,1] = 13-Jul-16,10.46,100.63,15.7,54.4,55656465
[1,2] = 12-Jul-16,10.47,100.64,15.7,54.4,55656465
[1,3] = 11-Jul-16,10.48,100.65,15.7,54.4,55656465
[1,4] = 10-Jul-16,10.49,100.66,15.7,54.4,55656465
}
In which each element is a string ("13-Jul-16,10.46,100.63,15.7,54.4,55656465" is a string).
I need to convert this to 6 vectors, something like
[a b c d e f] = ...
such a way, for example, for the 1st column, it would be
a = [13-Jul-16;12-Jul-16;11-Jul-16;10-Jul-16]
I tried to use cell2mat function, but for some reason it does not separate the fields into matrix elements, but it concatenates the whole string into something like
cell2mat(sLine)
ans =
13-Jul-16,10.46,100.63,15.7,54.4,5565646512-Jul-16,10.47,100.64,15.7,54.4,5565646511-Jul-16,10.48,100.65,15.7,54.4,5565646510-Jul-16,10.49,100.66,15.7,54.4,55656465
So, how can I solve this?
Update
I got the sLine matrix following the steps
pFile = urlread('http://www.google.com/finance/historical?q=BVMF:PETR4&num=365&output=csv');
sLine = strsplit(pFile,'\n');
sLine(:,1)=[];
Update
Thanks to #Suever I could get now the column dates. So the updated last version of the code is
pFile = urlread('http://www.google.com/finance/historical?q=BVMF:PETR4&num=365&output=csv');
pFile=strtrim(pFile);
sLine = strsplit(pFile,'\n');
sLine(:,1)=[];
split_values = regexp(sLine, ',', 'split');
values = cat(1, split_values{:});
values(:,1)
Your data is all strings, therefore you will need to do some string manipulation rather than using cell2mat.
You will want to split each element at the ,characters and then concatenate the result together.
sLine = {'13-Jul-16,10.46,100.63,15.7,54.4,55656465',
'12-Jul-16,10.47,100.64,15.7,54.4,55656465',
'11-Jul-16,10.48,100.65,15.7,54.4,55656465',
'10-Jul-16,10.49,100.66,15.7,54.4,55656465'};
split_values = cellfun(#(x)strsplit(x, ','), sLine, 'uniformoutput', 0);
values = cat(1, split_values{:});
values(:,1)
% {
% [1,1] = 13-Jul-16
% [2,1] = 12-Jul-16
% [3,1] = 11-Jul-16
% [4,1] = 10-Jul-16
% }
If you want it to be more concise, we can just use regexp to split it up instead of strsplit since it can accept a cell array as input.
split_values = regexp(sLine, ',', 'split');
values = cat(1, split_values{:});
Update
The issue with the code that you've posted is that there is a trailing newline in the input and when you split on newlines the last element of your sLine cell array is empty causing your issues. You'll want to use strtrim on pFile before creating the cell array to remove trailing newlines.
sLine = strsplit(strtrim(pFile), '\n');
sLine(:,1) = [];

Equivalent of adding strings to a loop, for strings (matlab)?

How would I be able to do the equivalent of this with strings:
a = [1 2 3; 4 5 6];
c = [];
for i=1:5
b = a(1,:)+i;
c = [c;b];
end
c =
2 3 4
3 4 5
4 5 6
5 6 7
6 7 8
Basically looking to combine several strings into a Matrix.
You're growing a variable in a loop, which is a kind of sin in Matlab :) So I'm going to show you some better ways of doing array concatenation.
There's cell strings:
>> C = {
'In a cell string, it'
'doesn''t matter'
'if the strings'
'are not of equal lenght'};
>> C{2}
ans =
doesn't matter
Which you could use in a loop like so:
% NOTE: always pre-allocate everything before a loop
C = cell(5,1);
for ii = 1:5
% assign some random characters
C{ii} = char( '0'+round(rand(1+round(rand*10),1)*('z'-'0')) );
end
There's ordinary arrays, which have as a drawback that you have to know the size of all your strings beforehand:
a = [...
'testy' % works
'droop'
];
b = [...
'testing' % ERROR: CAT arguments dimensions
'if this works too' % are not consistent.
];
for these cases, use char:
>> b = char(...
'testing',...
'if this works too'...
);
b =
'testing '
'if this works too'
Note how char pads the first string with spaces to fit the length of the second string. Now again: don't use this in a loop, unless you've pre-allocated the array, or if there really is no other way to go.
Type help strfun on the Matlab command prompt to get an overview of all string-related functions available in Matlab.
You mean storing a string on each matrix position? You can't do that, since matrices are defined over basic types. You can have a CHAR on each position:
>> a = 'bla';
>> b = [a; a]
b <2x3 char> =
bla
bla
>> b(2,3) = 'e'
b =
bla
ble
If you want to store matrices, use a cell array (MATLAB reference, Blog of Loren Shure), which are kind of similar but using "{}" instead of "()":
>> c = {a; a}
c =
'bla'
'bla'
>> c{2}
ans =
bla

MATLAB generate combination from a string

I've a string like this "FBECGHD" and i need to use MATLAB and generate all the required possible permutations? In there a specific MATLAB function that does this task or should I define a custom MATLAB function that perform this task?
Use the perms function. A string in matlab is a list of characters, so it will permute them:
A = 'FBECGHD';
perms(A)
You can also store the output (e.g. P = perms(A)), and, if A is an N-character string, P is a N!-by-N array, where each row corresponds to a permutation.
If you are interested in unique permutations, you can use:
unique(perms(A), 'rows')
to remove duplicates (otherwise something like 'ABB' would give 6 results, instead of the 3 that you might expect).
As Richante answered, P = perms(A) is very handy for this. You may also notice that P is of type char and it's not convenient to subset/select individual permutation. Below worked for me:
str = 'FBECGHD';
A = perms(str);
B = cellstr(reshape(A,7,[])');
C = unique(B);
It also appears that unique(A, 'rows') is not removing duplicate values:
>> A=[11, 11];
>> unique(A, 'rows')
ans =
11 11
However, unique(A) would:
>> unique(A)
ans =
11
I am not a matlab pro by any means and I didn't investigate this exhaustively but at least in some cases it appears that reshape is not what you want. Notice that below gives 999 and 191 as permutations of 199 which isn't true. The reshape function as written appears to operate "column-wise" on A:
>> str = '199';
A = perms(str);
B = cellstr(reshape(A,3,[])');
C = unique(B);
>> C
C =
'191'
'199'
'911'
'919'
'999'
Below does not produce 999 or 191:
B = {};
index = 1;
while true
try
substring = A(index,:);
B{index}=substring;
index = index + 1;
catch
break
end
end
C = unique(B)
C =
'199' '919' '991'

How can I concatenate strings in a cell array with spaces between them in MATLAB?

I want to concatenate (padding with spaces) the strings in a cell array {'a', 'b'} to give a single string 'a b'. How can I do this in MATLAB?
You can cheat a bit, by using the cell array as a set of argument to the sprintf function, then cleaning up the extra spaces with strtrim:
strs = {'a', 'b', 'c'};
strs_spaces = sprintf('%s ' ,strs{:});
trimmed = strtrim(strs_spaces);
Dirty, but I like it...
matlab have a function to do this,
ref:
strjoin
http://www.mathworks.com/help/matlab/ref/strjoin.html
strjoin
Join strings in cell array into single string
Syntax
str = strjoin(C) example
str = strjoin(C,delimiter)
Ex:
Join List of Words with Whitespace
Join individual strings in a cell array of strings, C, with a single space.
C = {'one','two','three'};
str = strjoin(C)
str =
one two three
Small improvement (?) on the answer by Alex
strs = {'a','b','c'};
strs_spaces = [strs{1} sprintf(' %s', strs{2:end})];
You can accomplish this using the function STRCAT to append blanks to all but the last cell of your cell array and then concatenate all the strings together:
>> strCell = {'a' 'b' 'c' 'd' 'e'};
>> nCells = numel(strCell);
>> strCell(1:nCells-1) = strcat(strCell(1:nCells-1),{' '});
>> fullString = [strCell{:}]
fullString =
a b c d e
Both join and strjoin are introduced in R2013a. However, the mathworks site about strjoin reads:
Starting in R2016b, the join function is recommended to join elements of a string array.
>> C = {'one','two','three'};
>> join(C) %same result as: >> join(C, ' ')
ans =
string
"one two three"
>> join(C, ', and-ah ')
ans =
string
"one, and-ah two, and-ah three"
Personally I like Alex' solution as well, as older versions of Matlab are abundant in research groups around the world.

Resources