I need help with for loops

I am new to matlab and I'm writing a for loop that will answer eather true or false whether a number in a vector is positive or negative. ie A = [-5 -3 2 37 -33 6] and answer B = [false false true true false true]. Any advice you may be able to give me?

4 commentaires

for i = 1:length(A)
if A(i) > 0
B(i) = 'true';
% elseif A(i) == 0
% B(i) = 'zero';
else
B(i) = 'false';
end
end
Mark Woolsey
Mark Woolsey le 1 Mai 2020
Thank you for your responce, but that did not work
Here is what I have
clc, clear
A = [-100 20 50 -2 -55 3 40 -27];
for i = 1:length(A);
if A(i) > 0
B(i) = 'true'
else
B(i) = 'false'
end
end
David Hill
David Hill le 1 Mai 2020
Modifié(e) : David Hill le 1 Mai 2020
Why do you need to use a loop?
B=A>=0;%logical array (why do you need 'true' and 'false'?) you will have to do either a string array or cell array
l=["false","true"];
C=l((A>=0)+1);%string array
h={'false','true'};
D=h((A>=0)+1);%cell array
Mark Woolsey
Mark Woolsey le 1 Mai 2020
It is an asignment that I need to use a for or while loop to answer the question.

Réponses (2)

Prasad Reddy
Prasad Reddy le 1 Mai 2020

0 votes

clc
clear all
A = [-100 20 50 -2 -55 3 40 -27]
B=zeros(1,length(A))
for i = 1:length(A)
if A(i) > 0
B(i) = true
else
B(i) = false
end
end
% This will work. but you will get 1 in place of true and 0 in place of false.
% please give upthumb if this works well.
% i am trying more specifically for your code.
% will update soon once got the answer.
Prasad Reddy
Prasad Reddy le 1 Mai 2020

0 votes

clc
clear all
A = [-100 20 50 -2 -55 3 40 -27]
for i = 1:length(A)
if A(i) > 0
B(i) = {'true'};
else
B(i) = {'false'};
end
end
B
% This is the final Answer.
% Hear you are trying to crete a string array B, which will have true and false.
% I think this is the only way in which you can do it.
% please provide up thumb if it works. Iworked for this problem for an hour.

1 commentaire

Mark Woolsey
Mark Woolsey le 1 Mai 2020
This will work if i remove the (' ') around the true false statements, but i get the answer with 0's and 1's. Is there a way to convert the 0's and 1's to true and false outside the loop?
If i leave this in (' '), I get this responce:
In an assignment A(:) = B, the number of elements in A and B must be the same.

Cette question est clôturée.

Produits

Clôturé :

le 20 Août 2021

Community Treasure Hunt

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

Start Hunting!

Translated by