for loop is not working correctly
1 view (last 30 days)
Show older comments
sidra Rafique
on 7 Jun 2020
Answered: Image Analyst
on 7 Jun 2020
filename = 'data.xlsx';
sheet = 4;
c=4;
r=16;
A=zeros(r,c);
redt =1.5;
for i=2:length(A)
xlRange = sprintf('A%d:D%d',i,i);
A=xlsread(filename,sheet,xlRange);
m=max(A);
T =A;
idx = A == m;
T(idx) = [];
W_delay=T*redt;
T(i,:)=W_delay;
xlswrite('delay.xlsx',T,'Sheet4');
end
Above is my code and i also have attached an excel data file. problem with this code is ,there is a problem with the for loop. its only printing 1st and last row in excel sheet. but i need all rows.. i am new to this looping structure please help me this. i am really worried about it.
waiting for kind response
thanks
1 Comment
per isakson
on 7 Jun 2020
Edited: per isakson
on 7 Jun 2020
The statement
xlswrite('delay.xlsx',T,'Sheet4');
overwrites the previous result in every iteration. And
T = A;
overwrites T
Accepted Answer
Image Analyst
on 7 Jun 2020
Try this:
filename = 'data.xlsx';
sheet = 4;
c=4;
r=16;
A=zeros(r,c);
redt =1.5;
T = zeros(r, 3); % Preallocate T
for row=2: r
% Get range: this row from column A to column D.
xlRange = sprintf('A%d:D%d', row, row);
% Read that range from the input workbook.
A = xlsread(filename, sheet, xlRange);
% Get the max value of that range.
m = max(A);
indexOfMax = A == m;
A(indexOfMax) = []; % Remove max value.
W_delay = A * redt; % Multiply by 1.5
% Insert into T matrix.
T(row,:) = W_delay;
end
% Now write the resulting T matrix out to our output workbook.
xlswrite('delay.xlsx',T,'Sheet4');
winopen('delay.xlsx');
It would be even better if you didn't call xlsread() inside the loop, but before the loop and just took A(row, 1:4) in the loop. It would be faster.
0 Comments
More Answers (0)
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!