convert a txt file to a structure
7 views (last 30 days)
Show older comments
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
Accepted Answer
Stephen23
on 26 Jul 2018
Edited: Stephen23
on 26 Jul 2018
cell2struct(num2cell(PVRead{2}),PVRead{1},1)
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
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
More Answers (0)
See Also
Categories
Find more on Whos in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!