What this programe do

2 次查看(过去 30 天)
licia attouche
licia attouche 2021-1-16
X=input('Donner une matrice dont les l'element sont ts differnets de zero);
[n,m]=size(X);
for i=1:n
for j=1:m
if X(i,j)<0
M(i,j)=0;
else
M(i,j)=1;
end
end
end
disp(M)
A=M.*X
B=(1-M).*X
  3 个评论
Ive J
Ive J 2021-1-16
@Valerio Virzi MATLAB is an interpreter not a compiler. And of course you can use that French sentence as input:
X = input('Donner une matrice dont les l''element sont ts differnets de zero')
% OR
X = input("Donner une matrice dont les l'element sont ts differnets de zero")
Delme
Delme 2021-1-16
@Ive J thanks for the correction! That´s neat!

请先登录,再进行评论。

回答(2 个)

Image Analyst
Image Analyst 2021-1-16
The double for loop can be done in a vectorized way in a single line of code instead of 9 lines of code (this is how most MATLAB programmers would do it):
% Ask user for a matrix.
X = input("Donner une matrice dont les l'element sont ts differnets de zero");
M = X >= 0; % Find positive elements.
disp(M)
% Get only the positive elements in A with the negative elements being set to 0.
A=M.*X
% Get only the negative elements in B with the positive elements being set to 0.
B=(1-M).*X
% Alternatively
B = ~M .* X;
The code basically gets the positive and negative elements according to what I said in my comments. Most (I hope) MATLAB programmers would also have put comments into that code, and would have chosen more descriptive variable names so other people, like you for example, could follow the code easier and not be left scratching their head wondering what the code does.

Delme
Delme 2021-1-16
You can run this example and have a look.
X= [-3 2 1
4 3 2 ];
[n,m]=size(X);
for i=1:n
for j=1:m
if X(i,j)<0
M(i,j)=0;
else
M(i,j)=1;
end
end
end
disp(X)
disp(M)
A=M.*X;
B=(1-M).*X;
disp(A)
disp(B)
This will give you the following:
-3 2 1
4 3 2
0 1 1
1 1 1
0 2 1
4 3 2
-3 0 0
0 0 0

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by