MATLAB Answers

Copy data from cell 1 of file 1 and paste in n cells in file 2

1 view (last 30 days)
s sule
s sule on 18 Jul 2021
Commented: Peter Perkins on 27 Jul 2021
I want to copy "x(1,3)" from file 1 and paste it to 72 cells of file 2 "y(1:72,3). I then need to skip a row in file 2 and copy "x(1,4)" from file 1 and paste it to the subsequent 72 cells of file 2 "y(74:145,3) and so on. I have x(1,3) --> x(1,100). I want to do all of these in a loop. As a starter I could not guess more than below. Thank you in advance for your advice.
ix = readtable('fil1.xlsx')
x=table2cell(ix);
iy = readtable('file2.xlsx');
y= table2cell(iy);
for m=1:72
y(m,3)=x(1,3);
end
for n=74:145
y(n,3)=x(1,4);
end
for o=147:218
y(o,3)=x(1,5);
end
  2 Comments
s sule
s sule on 18 Jul 2021
Thank you for your advice. Here are examples of the workbooks. I manually coppied C2, D2 and E2 from fil_1 and substituted it to the corresponding 72 cells in fil_2. I want to repeat the same process in a single loop let's say till N2 from fil_1. I also need to skip one row in fil_2 at the end of each loop.

Sign in to comment.

Accepted Answer

Simon Chan
Simon Chan on 18 Jul 2021
I try to use readcell in my example:
Since readcell will read the header as the first row, so what you want to copy becomes the second row instead of row 1.
Similarly, this is the reason why the first staring index is 2 instead of 1.
clear; clc;
A = readcell('fil_1.xls'); % Read the first file
B = readcell('fil_2.xls'); % Read the second file
idx = 3:14; % There are only 14 columns in your attached file, but you can change it to 100
start = 2:73:73*length(idx); % Starting index
finish = start + 71; % Ending index
for k = 1:length(idx)
B(start(k):finish(k),3) = A(2,idx(k));
end
B(cellfun(@(x) any(ismissing(x)), B)) = {''}; % Replace the missing cells with empty one
writecell(B,'fil_2new.xls'); % Write into a new file
  1 Comment
Peter Perkins
Peter Perkins on 27 Jul 2021
Using cell arrays is probably not the way to go. I don't see any attached spreadsheets, so hard to say, but the word "cell" in the title of this thread is likely a red herring. For tabular data (what's usually in a spreadsheet), tables are the way to go.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!