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 commentaires

KSSV
KSSV le 26 Juil 2018
Why don't you attach your text file? specify the error?
Stephen23
Stephen23 le 26 Juil 2018
"...each of these cell arrays is a 31x1 cell"
Actually the textscan format specifier '%f' returns a double array.
Ayman Fathy
Ayman Fathy le 26 Juil 2018
Could you please check the comment below. I attached the file and the error. Thanks a lot

Connectez-vous pour commenter.

 Réponse acceptée

Stephen23
Stephen23 le 26 Juil 2018
Modifié(e) : Stephen23 le 26 Juil 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 commentaires

Ayman Fathy
Ayman Fathy le 26 Juil 2018
Modifié(e) : Ayman Fathy le 26 Juil 2018
Thank you so much Stephen. It is almost working. I am getting this error Error using struct Invalid field name "End of PVObject pvModule"
This is the last value in the column as it is assigned to a NaN. Also when I call one of the variables for example: CellArea after I run your code it gives me this error: Undefined function or variable 'CellArea'. I think its because C is still not a structure
Ayman Fathy
Ayman Fathy le 26 Juil 2018
Modifié(e) : Ayman Fathy le 26 Juil 2018
I basically want to assign each value to its corresponding name so that when I call cellArea (for example) it gives me an answer of 50
Stephen23
Stephen23 le 26 Juil 2018
Modifié(e) : Stephen23 le 26 Juil 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 le 26 Juil 2018
Thank you so Much Stephen very much appreciated!!

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by