Better way to pull out values from a struct
1 次查看(过去 30 天)
显示 更早的评论
I have a matrix with a matrix CT of struct data called callsTable. I'm trying to pull out just one of the columns called Time and create a 1D vector using the following code. Is there a better way that I can do this? Currently, running the code I get the following error message.
Unable to perform assignment because the size of the left side is 28-by-1 and the size of the right side is
6-by-1.
for k=1:size(CT,1)
for i=size(CT(k),1)
T(:,i)=CT(k).callsTable.Time
end
end
0 个评论
回答(3 个)
Walter Roberson
2020-1-18
Times = arrayfun(@(S) S.callsTable.Time, CT, 'uniform', 0);
T = horzcat(Times{:});
The assignment to T will fail if the Time vectors were not all the same size.
0 个评论
Sam Litvin
2020-1-18
2 个评论
Walter Roberson
2020-1-18
time_lengths = arrayfun(@(S) length(S.callsTable.Time), CT);
max_time_lengths = max(time_lengths);
FirstN = @(V, N) V(1:N);
PadN = @(V, N) FirstN([V; zeros(N,1)]);
Times = arrayfun(@(S) PadN(S.callsTable.Time, max_time_lengths), CT, 'uniform', 0);
T = horzcat(Times{:});
Walter Roberson
2020-1-18
time_lengths = arrayfun(@(S) length(S.callsTable.Time), CT);
max_time_lengths = max(time_lengths);
FirstN = @(V, N) V(1:N);
PadN = @(V, N) FirstN([V; zeros(N,1)], N);
Times = arrayfun(@(S) PadN(S.callsTable.Time, max_time_lengths), CT, 'uniform', 0);
T = horzcat(Times{:});
Sam Litvin
2020-1-18
1 个评论
Walter Roberson
2020-1-18
FirstN: takes the first N elements of whatever is handed in
PadN : take whatever input is given and always add N zeros at the end of it, and then call FirstN to pull out the first N of whatever that ends up being
So for example, PadN([1;2;3], 7) would form [1;2;3;0;0;0;0;0;0;0] and then ask FirstN to take the first 7 of those, getting out [1;2;3;0;0;0;0] as the result.
There are other ways of constructing something like this, including
PadN = @(V, N) [V; zeros(N-length(V), 1)]
which does not require as many steps.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!