Extracting data from handle objects

조회 수: 16 (최근 30일)
Marc Laub
Marc Laub 2022년 11월 29일
답변: Askic V 2022년 11월 29일
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
Marc Laub
Marc Laub 2022년 11월 29일
Did my best to trace back the most valuable answers, except if the answer was within a comment...
Rik
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
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
value1_vec = 1×2
3 8
value2_vec
value2_vec = 1×11
-0.7549 1.3703 -1.7115 -0.1022 -0.2414 0.3192 2.3505 -0.6156 0.7481 -0.1924 0.8886

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by