Restructure/align struct by interpollation/padding

Having a 3x1 struct s with fields x and y, where (if represented in a form of a table):
x y
[1;2] ['a';'b']
[2;4] ['c';'d']
[1;3;4] ['f';'g';'h']
I need to restructure the struct so that the values in each field of x and y are padded/interpollated by zeros so that they are of a uniform size and linearly spaced, "aligned" so to say, based on the series of [1;2;3;4] and the y field "mirrors" the padding/interpollation of x. The desired result is this:
x y
[1;2;0;0] ['a';'b'; 0 ; 0 ]
[0;2;0;4] [ 0 ;'c'; 0 ;'d']
[1;0;3;4] ['f'; 0 ;'g';'h']
How do I achieve this in Matlab using it optimal methods like vectorization etc., please?

 採用された回答

Ameer Hamza
Ameer Hamza 2018 年 5 月 19 日

1 投票

Here is a possible solution
s(1).x = [1;2];
s(1).y = ['a';'b'];
s(2).x = [2;4];
s(2).y = ['c';'d'];
s(3).x = [1;3;4];
s(3).y = ['f';'g';'h'];
numberVector = min(vertcat(s.x)):max(vertcat(s.x))
s2 = repmat( struct('x', zeros(size(numberVector))', 'y', repmat('0', size(numberVector))') , size(s))
for i=1:length(s)
index = find(any(s(i).x'==numberVector',2));
s2(i).x(index) = numberVector(index)';
s2(i).y(index) = s(i).y;
end
s2 will contain the modified struct array.

2 件のコメント

Jiri Zurek
Jiri Zurek 2018 年 5 月 20 日
Excellent! Thank you. Also, it is nice code for me to learn Matlab a little more by studying it.
Ameer Hamza
Ameer Hamza 2018 年 5 月 20 日
You are welcome.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeStructures についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by