How to use the fields in the structure?
    7 次查看(过去 30 天)
  
       显示 更早的评论
    
My structure has 83 Fields, and each field has 1059 *3 Double. Firstly how do I access these fields from the structure and then how do I multiply a matrix(rotation matrix) on these fields?. I know that I have to use for loop to access all the values and I have found this code But I do not know how It does function.
       for i = fieldnames(markerStruct)'
       newMarkerStruct.(i{1}) = markerStruct.(i{1});
end
I understand that values from markerStruct gets copied to newmarkerStruct. But I don't understand what i{1} means and How the value is getting assigned.
0 个评论
采纳的回答
  Adam Danz
    
      
 2019-2-28
        
      编辑:Adam Danz
    
      
 2019-2-28
  
      I've responded to your quesitons below.  First I make some fake data to work with.
% Fake data
S.f1 = rand(1059, 3); 
S.f2 = rand(1059, 3); 
S.f3 = rand(1059, 3); 
"Firstly how do I access these fields from the structure?"
% Field f1 is accessed like this
S.f1
% or dynamically
fn = fieldnames(S);   %list of field names
S.(fn{1})
% add a field
S.f4 = rand(1059, 3); 
"How do I multiply a matrix(rotation matrix) on these fields?"
% rotation matrix
ry = [ cos(pi)  0  sin(pi);
    0        1    0       ;
    -sin(pi)  0  cos(pi)] ;
% Multiply the matrix by the first field . 
f1Rot = S.f1 * ry; 
"I know that I have to use for loop to access all the values "
% Actually, not true.  You can use structfun() to apply a function to all fields.  
% In this example, it's expected that all fields have 3 columns of data.
S2 = structfun(@(x) x * ry, S, 'UniformOutput', false); 
% But if you must use a loop
fn = fieldnames(S);   %list of field names
S2 = struct;          % create new structure (no fields yet)
for i = 1:length(fn)
    S2.(fn{i}) = S.(fn{i}) * ry; %store results in a new struct with same field names
end
"I have found this code But I do not know how It does function"
% This for-loop does nothing.  It's just looping through each field and re-assigning the identical value.
% It's like A = A.  
for i = fieldnames(markerStruct)'
    newMarkerStruct.(i{1}) = markerStruct.(i{1});
end
fieldnames() lists all field names in a cell array of strings.
6 个评论
更多回答(0 个)
另请参阅
类别
				在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


