1

I have a set of data that is <106x25 double> but this is inside a struct and I want to extract the data into a matrix. I figured a simple FOR loop would accomplish this but I have hit a road block quite quickly in my MATLAB knowledge.

This is the only piece of code I have, but I just don't know enough about MATLAB to get this simple bit of code working:

>> x = zeros(106,25); for i = 1:106, x(i,:) = [s(i).surveydata]; end
??? Subscripted assignment dimension mismatch.

's' is a very very large file (in excess of 800MB), it is a <1 x 106 struct>. Suffice it to say, I just need to access a small portion of this which is s.surveydata where most rows are a <1 x 25 double> (a row vector IIRC) and some of them are empty and solely return a [].

s.surveydata obviously returns the results for all of the surveydata contained where s(106).surveydata would return the result for the last row. I therefore need to grab s(1:106).surveydata and put it into a matrix x. Is creating the matrix first by using x = zeros(106,25) incorrect in this situation?

Cheers and thanks for your time!

Ryan

4

3 回答 3

2

The easiest, cleanest, and fastest way to write all the survey data into an array is to directly catenate it, using CAT:

x = cat(1,s.surveydata);

EDIT: note that if any surveydata is empty, x will have fewer rows than s has elements. If you need x to have the same amount of rows as s has elements, you can do the following:

%# find which entries in s have data
%# note that for the x above, hasData(k) contains the 
%# element number in s that the k-th row of x came from
hasData = find(arrayfun(@(x)~isempty(x.surveydata),s));

%# initialize x to NaN, so as to not confuse the
%# real data with missing data entries. The call
%# to hasData when indexing makes this robust to an 
%# empty first entry in s
x = NaN(length(s),length(s(hasData(1)).surveydata);

%# fill in only the rows of x that contain data
x(hasData,:) = cat(1,s(hasData).surveydata);
于 2012-04-14T22:11:40.740 回答
1

No, creating an array of zeroes is not incorrect. In fact it's a good idea. You don't have to declare variables in Matlab before using them, but for loops, pre-allocating has speed benefits.

x = zeros(size(s), size(s(1)));

for i = 1:106
    if ~isempty(s(i).surveydata)
        x(i, :) = s(i).surveydata;
    end
end

Should accomplish what you want.

EDIT: Since OP indicated that some rows are empty, I accounted for that like he said.

于 2012-04-14T18:45:48.480 回答
0

what about this? what s is?

if s(i).surveydata is scalar:

x = zeros(106,25); 
for i = 1:106
x(i,1) = [s(i).surveydata]; 
end

I am guessing that is what you want tough it is not clear at all :

if s(i).surveydata is row vector:

x = zeros(106,25); 
for i = 1:106
x(i,:) = [s(i).surveydata]; 
end

if s(i).surveydata is column vector:

x = zeros(106,25); 
for i = 1:106
x(i,:) = [s(i).surveydata]'; 
end
于 2012-04-14T18:29:03.323 回答