I have a textfile that I need to read into matlab. I want to implement something like a java LinkedHashMap in Matlab using structures. my textfile is like this
3-1 33.33 37.58
3-1 66.67 20.47
3-2 33.33 41.64
3-2 66.67 24.42
I read the entire file into array [a,x,y] where a is a cell array containing 3-1 ad 3-2
I need the structure to have its field names as a(1) or a(2) but unfortunately matlab gives me error. The reason is that I need to check if for instance a(1) is already a structure field name I concat the values to the previous values; if not, make a new field name with the respected values. the code is:
[a,x,y]=textread('mytxt.txt', '%q%f%f','commentstyle','matlab');
s.a(1)=[x(1),y(1)];
for j=2:length(a)
if isfield(s,a(1))==0
s.a(j)=[x(j),y(j)];
else
temp = s.a(j);
C = concat(1,temp,[x(j),y(j)];
s.a(j) = C
end
end
Presumably you want to have s as a structure with fields 3-1, 3-2, …, 3-n. I also think you want to create using MATLAB’s dynamic field names.
To access the fields dynamically through the cells in the cell-array a you need to do something similar to:
Make a note of the different uses of parentheses () and braces {}. The parentheses are for indicating dynamic field-names as in s.(str) where str is a character array. The braces are used to index into the cell array a as in a{j} gives the character array of the jth cell in a.
Finally, your proposed field-names (3-1, 3-2, … etc) are not legal MATLAB field-names because of the hyphen ‘-‘ and they do not begin with a letter, [a-zA-Z]. So, you need to replace the hyphen with another character, for example an underscore and append a letter to the start of the proposed field-name.
Replacing hyphen using strrep as in
a=strrep(a,’-‘,’_’);
Appending a letter to the start of the field-name
a=cellfun(@(str) [‘a_’ str],a,’uniformoutput’,0)
This work can be done right after you finish reading the file into matrices a, x, and y