Help me to run the code

조회 수: 11 (최근 30일)
Wesam abdulaziz
Wesam abdulaziz 2023년 4월 9일
답변: Alexander 2025년 10월 7일 22:05
% Creating variables
aSca = 2.5 * 1023;
bSca = 4 + 2i;
cVect = (6:-0.6:-5)';
dMat = diag(2*ones(4,1));
eMat = randi([-2 2],4,3);
% Common functions and indexing
fSum = sum(eMat);
dMat(:,3) = 1;
gSub = eMat(1:3,1:2);
dMat(:,end) = [];
shaimaa_Al_Otaibi_Computer_Engineering = [dMat eMat];
shaimaa_Al_Otaibi_Computer_Engineering = round(shaimaa_Al_Otaibi_Computer_Engineering);
fMat = 5:10;
% Control statements
% a)
xVec = 0:0.1:2;
% b)
sum_n = 0;
n = 0;
while sum_n <= 500
n = n + 1;
sum_n = sum_n + n;
end
% c)
if aSca > bSca
disp('aSca is greater than bSca.')
else
disp('bSca is greater than aSca.')
end
aSca is greater than bSca.
% d)
x = 3;
switch x
case 1
disp('x is 1.')
case 2
disp('x is 2.')
case {3,4}
disp('x is 3 or 4.')
otherwise
disp('x is not 1, 2, 3, or 4.')
end
x is 3 or 4.
  댓글 수: 1
Dyuman Joshi
Dyuman Joshi 2023년 4월 9일
Format your code properly and run the code. What seems to be the problem?

댓글을 달려면 로그인하십시오.

답변 (1개)

Alexander
Alexander 2025년 10월 7일 22:05
c) Could be a problem with complex numbers and older Matlab version. Here a solution with right format:
%% Repro: deterministic random numbers
rng(0,'twister');
%% Creating variables
aSca = 2.5 * 1023; % scalar (double)
bSca = 4 + 2*1i; % complex scalar; use 1i to avoid accidental shadowing
cVect = (6:-0.6:-5)'; % column vector
dMat = diag(2*ones(4,1)); % 4x4 diagonal matrix with 2 on the diagonal
eMat = randi([-2 2],4,3); % 4x3 integer matrix in [-2,2]
%% Common functions and indexing
fSum = sum(eMat,1); % column sums (1x3)
dMat(:,3) = 1; % set 3rd column to ones
gSub = eMat(1:3,1:2); % 3x2 submatrix
dMat(:,end) = []; % remove last column -> dMat is now 4x3
shaimaa_Al_Otaibi_Computer_Engineering = [dMat eMat]; % 4x6 concatenation
shaimaa_Al_Otaibi_Computer_Engineering = round(shaimaa_Al_Otaibi_Computer_Engineering); % redundant here but OK
fMat = 5:10; % row vector 1x6
%% Control statements
% a) vector from 0 to 2 with step 0.1
xVec = 0:0.1:2;
% b) smallest n with cumulative sum > 500 (while-loop)
sum_n = 0;
n = 0;
while sum_n <= 500
n = n + 1;
sum_n = sum_n + n;
end
% (optional) closed-form alternative without loop
n2 = ceil( (sqrt(1 + 8*500) - 1)/2 );
sum_n2 = n2*(n2+1)/2;
% c) comparing a real scalar with a complex number:
% relational operators (< <= > >=) are undefined for complex values.
% Compare against the magnitude instead.
if aSca > abs(bSca)
disp('aSca is greater than |bSca|.');
else
disp('|bSca| is greater or equal to aSca.');
end
aSca is greater than |bSca|.
% d) switch-case example
x = 3;
switch x
case 1
disp('x is 1.');
case 2
disp('x is 2.');
case {3,4}
disp('x is 3 or 4.');
otherwise
disp('x is not 1, 2, 3, or 4.');
end
x is 3 or 4.

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by