Questions about data types and tables

4 views (last 30 days)
Data types is not strong side in Matlab, so i'm hoping that someone can help me. See comments in code
%% I'm storing data types of different lenghts as a table. Is a table a good idea?
X1=[9 6 9;3 2 7];
X2=[0 2;4 0];
X3=[3 1 2; 8 9 7];
X=table(X1,X2,X3)
X = 2×3 table
X1 X2 X3 ___________ ______ ___________ 9 6 9 0 2 3 1 2 3 2 7 4 0 8 9 7
%% The code bellow finds the longest entity in the table and writes out any entities shorter,
% X2 in this case.
len=table2array(varfun(@(x) size(x,2),X));
lmax=max(len);
idrest=find(len<lmax);
X(:,idrest)
ans = 2×1 table
X2 ______ 0 2 4 0
%% Now i wish to "fill-out" the shorter enteties by adding 'Nan' as seen bellow.
% I now wish to store this new strucutre in the place of the original. This
% is the problem that I can't solve.
for i=idrest(1):idrest(end)
temp=table2array(X(:,i));
temp(:,end+1:lmax)=nan
X.X(:,i)=temp %% Here's the issue
end
temp = 2×3
0 2 NaN 4 0 NaN
Unable to perform assignment because the size of the left side is 2-by-1 and the size of the right side is 2-by-3.

Accepted Answer

Dave B
Dave B on 15 Nov 2021
Edited: Dave B on 15 Nov 2021
In your loop, X(:,i) is the contents of the table variable, and you're using it with dot indicating it as the name of the variable.
I believe this is the code you're looking for (I added another variable to make it a slightly more robust test)
X1=[9 6 9;3 2 7];
X2=[0 2;4 0];
X3=[3 1 2; 8 9 7];
X4=[0;2];
X=table(X1,X2,X3,X4)
X = 2×4 table
X1 X2 X3 X4 ___________ ______ ___________ __ 9 6 9 0 2 3 1 2 0 3 2 7 4 0 8 9 7 2
len=table2array(varfun(@(x) size(x,2),X)); % or varfun(@(x)size(x,2),X,'OutputFormat','uniform')
lmax=max(len);
idrest=find(len<lmax);
for i = idrest
temp=X.(i);
temp(:,end+1:lmax)=nan;
X.(i)=temp;
end
X
X = 2×4 table
X1 X2 X3 X4 ___________ _______________ ___________ _______________ 9 6 9 0 2 NaN 3 1 2 0 NaN NaN 3 2 7 4 0 NaN 8 9 7 2 NaN NaN

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!