Extracting data from handle objects
10 次查看(过去 30 天)
显示 更早的评论
Hey, I have following problem.
I have multiple handle class objects which all have a propertie which can either be a scalar or a vector/matrix.
I now need a way to extract the last values of those vactors/matrices from all objects, so that they form a vector again.
So for example:
obj(1).value1=[1,2,3];
obj(1).value2=[0,0,0;0.1,0.2,0.3;0.9,0.8,0.7];
obj(2).value1=[1,2,3,4,5];
obj(2).value2=[0,0,0,0,0;0.9,0.7,0.8,0.6,0.5;0.1,0.2,0.3,0.4,0.5];
...
I now need to extract the data like
value1_vector=[3,5];
value2_vector=[0,0.3,0.7;0,0.5,0.5];
At the same time, these vectors/matrices have no fixed length and I dont know the length at the start. So it would be better to save same as a cell? Would that make the extracting of the values above easier?
Maybe a change in the size is not preferable when in future the code might be tranfered to a mexfile, where a size change while runtime is inmpossible.
Many thanks in advance
3 个评论
Rik
2022-11-29
The best strategy for storing your data depends on what you want to do next.
Do not reject a solution with a loop out of hand. Loops are fast and are easy for Matlab (or a human) to translate to C(++).
采纳的回答
Askic V
2022-11-29
I hope this helps a bit:
clear
clc
obj_arr = struct('value1',[], 'value2',[]);
rng(0)
% Initialize obj_array
for ii = 1:2
% generate random number of elements
nr_el = randi([2 6], 1,1);
obj_arr(ii).value1 = randi(10,1,nr_el);
obj_arr(ii).value2 = randn(nr_el,nr_el);
end
% Determine the size of obj_arr
N = length(obj_arr);
% vectors to store values
value1_vec = zeros(1, N);
value2_vec = [];
for ii = 1:N
value1_vec(ii) = obj_arr(ii).value1(end);
[r2, c2] = size(obj_arr(ii).value2);
for jj = 1:r2
value2_vec = [value2_vec, obj_arr(ii).value2(jj,c2)];
end
end
value1_vec
value2_vec
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!