evaluating elements of a vector in a function file
Mostra commenti meno recenti
Hi, guys, I am not much of an experienced programmer ,this might sound stupid but I am having trouble with a code below .I want to use each element of my input vector taken in by the function I created. I want to use each element and whatever answers I get from the evaluation of each element, I want it to be stored in a vector that I wish to return to where the function was called , however, it seems like the forloop is not working well as it stops after evaluating one element . what am I doing wrong ?
function [ M ] = new_vector(x)
%This function takes in vector containing various x values
%The the sum of M(1,2,3..) is evaluated at that specific x and the value is appended to the matrix M
M = zeros(1,6);
for i = 1:6
M1 = RA*(x(1,i));
sum_of_Ms = 0+M1;
M2 = RB*(x(1,i)-5);
if M2 <= 0
break
else
sum_of_Ms = sum1+M2;
end
M3 = -w*(x(1,i)-7.5);
if M3 <= 0
break
else
sum_of_Ms = sum_of_Ms+M3;
end
M4 = RC*(x(1,i)-10);
if M4 <= 0
break
else
sum_of_Ms = sum_of_Ms+M4;
end
M5 = RD*(x(1,i)-15);
if M2 <= 0
break
else
sum_of_Ms = sum_of_Ms+M5;
end
M6 = RE*(x(1,i)-20);
if M6 <= 0
break
else
sum_of_Ms = sum_of_Ms+M6;
end
M(1,i)= sum_of_Ms
end
end
Risposta accettata
Più risposte (1)
Massimo Zanetti
il 9 Ott 2016
2 voti
First, the "for" loop stop at first iteration because it enters in one "break" condition. Second, in order to fix it, please give an explanation of what your algorithm should do with such vector x, then I can try to help you do the work. What kind of vector is x? What are RA,RB,RD?
2 Commenti
Guillaume
il 9 Ott 2016
@ANOZ21, yes, it is clear that you don't know what break does as none of them make any sense in your code as it is.
break immediately stops the for loop and jumps to just after its end. Since there's nothing after that in your code, in effect break ends the function. As you only assign values other than zero to the output at the end of the loop, you're returning a vector of 0 as soon as you hit a break.
It looks like you hit a break at the first if since otherwise you'd be executing the
else
sum_of_Ms = sum1+M2;
which would result in an error since sum1 is not defined.
ANOZ21
il 9 Ott 2016
Categorie
Scopri di più su Common Operations in Centro assistenza e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!