make vectors from excel file equal length in matlab

To make vectors from an excel file of different lengths to be equal in length in MATLAB, you can follow the following steps:

  1. Import the Excel file using xlsread function in MATLAB.
main.m
[num,txt,raw] = xlsread('example.xlsx');
41 chars
2 lines
  1. Determine the maximum length of the vectors.
main.m
max_len = max(cellfun(@(x) numel(x), raw)); 
45 chars
2 lines
  1. Add padding to the vectors with length less than the maximum length.
main.m
for i = 1:size(raw,1)
    row = raw(i,:);
    row(cellfun(@isempty,row)) = {0};
    row = [row{:}];
    raw{i,1:numel(row)} = row;
    raw(i,numel(row)+1:end) = {NaN};
end
172 chars
8 lines
  1. Extract the vectors from the cell array.
main.m
data = cell2mat(raw);
vectors = data(:,any(~isnan(data)));
59 chars
3 lines

Now, all vectors in the excel file have been padded to equal length and can be used in MATLAB as needed.

related categories

gistlibby LogSnag