Hi, my excel file (Book2) contains 20x3 arrays with integer values. I want to run the following 'for loop' and 'if loop' with logical operations on Matlab and then write 'string' values in a new column of the same excel file. Please help me to correct the code. Thanks.
F = xlsread('Book2.xlsx');
N = length(F(:, 2));
for i = 1 : N
if ((F(i, 2) >= 7 && F(i, 2) < 27) && (F(i, 3) >= 28 && F(i, 3) < 50) && (F(i, 1) <= 52))
xlswrite('F.xlsx', (i, 4), {'Loam'});
else
xlswrite('F.xlsx', (i, 4), {'Null'});
end
end

 Réponse acceptée

darova
darova le 19 Sep 2019

0 votes

I suggest you to write all you want in cell array then write it to Excel file
A = cell(5,1); % preallocate cell array
for i = 1:5
if mod(i,2)
A{i} = 'hi';
else
A{i} = 'by';
end
end
fname = 'b.xlsx';
sheet = 2;
xlRange = 'A1';
xlswrite(fname,A,sheet,xlRange) % write cell array into 2d sheet on A1 position

4 commentaires

Sangay Nidup
Sangay Nidup le 20 Sep 2019
Hi Darova, thanks for the suggestion. I tried it and it works, but it is writing letters in different cells. Is there anyway that the whole word is written in one cell? For example, instead of printing 'h' in one cell and 'i' in next cell, to print 'hi' in one cell.
Also, it is giving some warning while trying to write an excel with 'xlswrite'. I guess, this is due to the mac version.
Thank you.
darova
darova le 20 Sep 2019
Hi, it's weird. WOrks for me
11Capture.PNG
Is A array still size of 5x1 after for loop?
What kind of warnings?
Sangay Nidup
Sangay Nidup le 20 Sep 2019
Hi,
It works on the Windows version of Matlab. Thanks a lot. You saved my day.
darova
darova le 20 Sep 2019
you are welcome

Connectez-vous pour commenter.

Plus de réponses (1)

Sangay Nidup
Sangay Nidup le 19 Sep 2019

0 votes

Hi, I have modified my code little bit as given below. I could write into an excel file but instead of writing value "Loam" or "Null" it is giving in number. For example, instead of "Loam", it's giving 4 and same case with the "Null".
F = xlsread('Book2.xlsx');
N = length(F(:, 2));
a = zeros(N, 1);
for i = 1 : 20
if ((F(i, 2) >= 7 && F(i, 2) < 27) && (F(i, 3) >= 28 && F(i, 3) < 50) && (F(i, 1) <= 52))
a(i, 1) = fprintf('Loam');
xlswrite('b.xlsx', a);
else
a(i, 1) = fprintf('Null');
xlswrite('b.xlsx', a);
end
end
How can I get in string instead of integer?

Community Treasure Hunt

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

Start Hunting!

Translated by