Rego
Rego

Reputation: 1116

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)

Upvotes: 1

Views: 90

Answers (1)

Suever
Suever

Reputation: 65430

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) = [];

Upvotes: 2

Related Questions