for loop is not working correctly

1 回表示 (過去 30 日間)
sidra Rafique
sidra Rafique 2020 年 6 月 7 日
回答済み: Image Analyst 2020 年 6 月 7 日
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 件のコメント
per isakson
per isakson 2020 年 6 月 7 日
編集済み: per isakson 2020 年 6 月 7 日
The statement
xlswrite('delay.xlsx',T,'Sheet4');
overwrites the previous result in every iteration. And
T = A;
overwrites T

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

採用された回答

Image Analyst
Image Analyst 2020 年 6 月 7 日
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 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by