doing operations on 1xN struct
4 ビュー (過去 30 日間)
古いコメントを表示
i have a structure that holds some data,
the structure is an array of structures (size of 1xN, N is an integer)
one of the data each struct holds is a 3 by 3 matrics with xyz positions of 3 points in space.
so a 1x2 structure will hold 2 matrics 3x3.
i need the square root of each row, but i dont know how to do it without a loop.
is there a way to get the square root of each row, within all the structures in the array without a loop?
0 件のコメント
回答 (1 件)
Voss
2024 年 9 月 30 日
Constructing a structure array:
N = 2;
S = struct('matrix_field',permute(num2cell(rand(3,3,N),[1 2]),[1 3 2]),'other_field',{'something','else'})
S(1)
S(2)
If it's convenient for subsequent operations you need to do, you can concatenate all N 3x3 matrices into a 3x3xN array and take the square root of that, resulting in another 3x3xN array:
M = sqrt(cat(3,S.matrix_field));
disp(M)
Otherwise, you can use arrayfun, which is a loop, and which results in a cell array of 3x3 matrices:
C = arrayfun(@(s)sqrt(s.matrix_field),S,'UniformOutput',false)
celldisp(C)
Since that gives you a cell array, it's convenient to put the result in a new field in the original structure array, if that's ultimately what you want:
[S.sqrt_matrix_field] = C{:}
S(1).sqrt_matrix_field
S(2).sqrt_matrix_field
Both of those approaches take the square root of each element of each matrix. Since you mentioned taking the square root of each row of each matrix, I'll make a guess at what that means (squaring each element, summing across each row, and taking the square root of that), and show it using both approches.
First the concatenation approach:
M = sqrt(sum(cat(3,S.matrix_field).^2,2));
disp(M)
It may be convenient to permute that 3x1xN array into a 3xN matrix:
M = permute(M,[1 3 2])
And the arrayfun approach:
C = arrayfun(@(s)sqrt(sum(s.matrix_field.^2,2)),S,'UniformOutput',false)
celldisp(C)
And putting those results into the original structure array:
[S.sqrt_matrix_field] = C{:}
S(1).sqrt_matrix_field
S(2).sqrt_matrix_field
You could also concatenate the contents of each cell of C together to form a 3xN matrix:
M = [C{:}]
but if that's the form of the result you need, it's better to skip the cell array entirely and use the concatenation approach.
0 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!