loop for matlab array

i have a problem with for loop.we have a vector a=[0 1 1 1 0] and a vector b=[1 1 1 1 1]
for i = 1:length(a)
if a(i)==0
c = [-1.*b] ;
else if a(i)==1
c = [1.* b];
end
end
the loop works only for a(1)=0 and stops.

Respuestas (3)

Geoff Hayes
Geoff Hayes el 23 de Nov. de 2016

0 votos

Try removing the space between the else if. Re-write this as
if a(i)==0
c = [-1.*b] ;
elseif a(i)==1
c = [1.* b];
end

4 comentarios

best16 programmer
best16 programmer el 23 de Nov. de 2016
thank you for your answer,but still does not works,even i removed the space
Image Analyst
Image Analyst el 23 de Nov. de 2016
What are you trying to do? Each iteration you make up a c array which is different on each iteration. c is not a single number you know. It's a vector.
best16 programmer
best16 programmer el 23 de Nov. de 2016
yes i know,i'm trying to display the result c in a edit text
Image Analyst
Image Analyst el 23 de Nov. de 2016
Then just do
handles.edit1.String = sprintf('%d ', c);
This will convert the vector to a string and put it into the edit text box on your GUI.

Iniciar sesión para comentar.

Image Analyst
Image Analyst el 23 de Nov. de 2016

0 votos

Maybe you wanted elseif instead of "else if". This works and does several iterations:
a=[0 1 1 1 0]
b=[1 1 1 1 1]
for i = 1:length(a)
if a(i)==0
c = [-1.*b]
elseif a(i)==1
c = [1.* b]
end
end
Of course there are better ways to do that and no experienced MATLAB programmer would do that operation like that.

3 comentarios

best16 programmer
best16 programmer el 23 de Nov. de 2016
Editada: best16 programmer el 23 de Nov. de 2016
i'm a beginner in matlab.i removed the space but still not working.do you have any suggestions.thanks for advance
best16 programmer
best16 programmer el 23 de Nov. de 2016
the problem is how can we display all the c values in a edit text
Image Analyst
Image Analyst el 23 de Nov. de 2016
They will all be displayed because there is no semicolon at the end of the line. Did you actually try it and look in the command window?

Iniciar sesión para comentar.

Andrei Bobrov
Andrei Bobrov el 23 de Nov. de 2016

0 votos

c = (a(:)*2 - 1)*b(:)';
or
c = (a(:)*2 - 1).*b(:);

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Productos

Etiquetas

Preguntada:

el 23 de Nov. de 2016

Editada:

el 23 de Nov. de 2016

Community Treasure Hunt

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

Start Hunting!

Translated by