Reputation: 1301
I have a struct with several fields, some that should be numeric, and some that should be char. However, after my use of regexp
I have chars in the fields that I want to use as numbers.
For example:
foo.str = 'one';
foo.data = '1';
foo(2).str = 'two';
foo(2).data = '2';
In my dreams I could do: foo.data = str2double(foo.data)
, but this does not work.
I could iterate through the struct, but that's only an ok option. It's a long struct (100,000) with about 20 files.
for i = 1:length(foo)
foo(i).data = str2double(foo(i).data);
end
Any ideas?
Upvotes: 4
Views: 2157
Reputation: 30589
Here is a fairly compact solution that deal
s numerical values back into each foo.data
:
fdnc = num2cell(str2double({foo.data}));
[foo.data] = deal(fdnc{:});
Remember to clear and redefine foo
when testing.
EDIT: Fixed vertcat
problem with multiple digits. Thanks, nispio.
Upvotes: 2
Reputation: 112749
A little cumbersome, but this works; no loops:
N = length(foo);
[aux_str{1:N}] = deal(foo.str);
[aux_data{1:N}] = deal(foo.data);
aux_data = mat2cell(str2double(aux_data),1,ones(1,N));
foo = cell2struct([aux_str; aux_data],{'str','data'},1);
Upvotes: 1
Reputation: 10676
Collect all elements from the subfield and call str2double once:
str2double({foo.data})
Upvotes: 3