convert a txt file to a structure

7 views (last 30 days)
Hello, I read and text scanned a text file into a variable. This variable (1x2 cell) now contains 2 cell arrays each of these cell arrays is a 31x1 cell. One of them contain the names and the other the values. how do I assign each name to its corresponding value? Here is my code but its not working:
clear all;
clc;
PVData = 'w:\Users\james\Documents\MATLAB\readfile.txt';
fid=fopen(PVData);
PVRead=textscan(fid,'%s %f %*[^\n]','delimiter','=','EmptyValue',nan);
fclose(fid);
names = PVRead(1);
values = PVRead(2);
structarray = cell2struct(values, names, 2);
  3 Comments
Stephen23
Stephen23 on 26 Jul 2018
"...each of these cell arrays is a 31x1 cell"
Actually the textscan format specifier '%f' returns a double array.
Ayman Fathy
Ayman Fathy on 26 Jul 2018
Could you please check the comment below. I attached the file and the error. Thanks a lot

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 26 Jul 2018
Edited: Stephen23 on 26 Jul 2018
Method one: cell2struct:
cell2struct(num2cell(PVRead{2}),PVRead{1},1)
Method two: struct:
C = [PVRead{1},num2cell(PVRead{2})].'
S = struct(C{:})
Tested:
>> PVRead = {{'anna';'bob';'cat'},[1;2;3]};
>> C = [PVRead{1},num2cell(PVRead{2})].';
>> S = struct(C{:})
S =
scalar structure containing the fields:
anna = 1
bob = 2
cat = 3
>> S = cell2struct(num2cell(values),names,1)
S =
scalar structure containing the fields:
anna = 1
bob = 2
cat = 3
  4 Comments
Stephen23
Stephen23 on 26 Jul 2018
Edited: Stephen23 on 26 Jul 2018
>> str = fileread('readfile.txt');
>> tkn = regexp(str,'^\s+([A-Za-z]\w+)=([^\n\r]+)\s+$','tokens','lineanchors');
>> tkn = vertcat(tkn{:}).';
>> vec = str2double(tkn(2,:));
>> idx = ~isnan(vec);
>> tkn(2,idx) = num2cell(vec(idx));
>> tkn(:,strcmp('Flags',tkn(1,:))) = [];
>> S = struct(tkn{:});
>> S.CellArea
ans =
241
>> S.Gamma
ans =
1.3240
>> S.Manufacturer
ans =
Bosch Solar Energy AG
Ayman Fathy
Ayman Fathy on 26 Jul 2018
Thank you so Much Stephen very much appreciated!!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!