logical operators problem T_T

Hi,
I am new to Matlab and still trying to understand its usage. I'm trying to read data from a .dat file and solve simple mathematical problem. When I tried to enter one sample data it came out right, but once I tried 2 rows of data, this message occurred. Please help me.
The error ??? Operands to the and && operators must be convertible to logical scalar values.
Error in ==> magnitude at 14
if wm>0.1 && wm<=9.5;
my .m file is like this. Thank you for your help :)
% This file tries to sort all data and changes all magnitude to bodywave
% magnitude
historicalinput = load('hiseq.dat');
% Arrangement of data = year, lat, long, depth, rm, sm, bm, wm
year = historicalinput (:,1);
lat = historicalinput (:,2);
long = historicalinput (:,3);
depth = historicalinput (:,4);
rm = historicalinput (:,5);
sm = historicalinput (:,6);
bm = historicalinput (:,7);
wm = historicalinput (:,8);
% Calculation of each magnitude
if wm>0.1 && wm<=9.5;
wm = wm
% change rm to wm
elseif rm>0.1 && rm<9.5;
wm = 0.690*rm+1.7738
% change sm to wm
elseif sm>0.1 && sm <9.5;
wm = 1.2765*sm-1.0825
%change bm to wm
else bm>0.1 && bm<9.5;
wm = 0.7813*bm+1.6562
end
% print all data in new .dat file
Filename = 'results';
FID = fopen (Filename, 'w');
if FID < 0, error('Cannot open file'); end
data = [year', lat', long', depth', rm', sm', bm', wm'];
fprintf(FID, '%g %g %g %g %g %g %g %g %g¥n', data');
fclose(FID)

1 个评论

ok, I forgot,
my input data was
1973 4.4 96.33 33 0 0 4.4 0
1975 9.3 89.05 46 3.1 0 0 0

请先登录,再进行评论。

 采纳的回答

The error message means, that wm is not a scalar, but && needs scalar logical arguments.
Do you want
if any(wm>0.1 && wm<=9.5)
or
if all(wm>0.1 && wm<=9.5)
?

3 个评论

I got confused here. wm is scalar, if I change only keeping to wm<=9.5, there result came out nicely.
Why this happen?
How is wm a scalar when you say this:
wm = historicalinput (:,8);
The colon means "all rows" so if historicalinput is a 2D array, wm is a column vector, taken from the 8th column of historicalinput.
"if wm<=9.5" performs implicitely a "if all(wm<=9.5) && ~isempty(wm)". This automatic conversion is hard to debug and therefore it is a good programming practize to avoid non-scalar IF and WHILE expressions.

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by