How to select one element of vector and divide it on the summation of the rest elements???

2 vues (au cours des 30 derniers jours)
Hi :)
How to select one element of vector and divide it on the summation of the rest of the elements???
I am not quit sure what is wrong with my code , I really appreciate if any one can help with that ?
a = [1 2 3 4 5 6]; %this is my vector
for k = 1:6;
x(k)=a(k); %select one element of the vector
b = a(a~=x); %create new vector not contain the above element
y(k)=sum(b); % Find the summation of the rest of elements
h(k)=x(k)/y(k); Finally divide the select element on the summation
end
I got this error message :(
Error using ~= Matrix dimensions must agree.
Thank you very much in advance
  2 commentaires
Guillaume
Guillaume le 27 Août 2015
Stephen has given you a much better way to implement your code, but the reason your code is failing is simply due to the use of x(k) instead of x.
Before the loop starts, the variable x does not exists. On the first pass of the, matlab creates it and assigns a(1) to x. The loop proceeds with a matrix versus scalar comparison which causes no problems.
On the second pass of the loop, k = 2, the assignment x(k)=a(k) causes matlab to increase the size of x to 2 elements, keeps element 1 to value you've previously assigned, and puts a(2) into x(2). x is thus now [1 2]. You then have a~=x where you're trying to compare a 6 element array with a 2 element array. Matlab rightfully complains that the dimensions must agree.
If you'd just used x=a(k) and h(k)=x/y(k) everything would have been fine.
Hind Albasry
Hind Albasry le 28 Août 2015
You are absolutely right . Thank you for the explanation , appreciate that :)

Connectez-vous pour commenter.

Réponse acceptée

Stephen23
Stephen23 le 27 Août 2015
Modifié(e) : Stephen23 le 27 Août 2015
This is much easier and faster to solve using vectorized code:
>> a = [1,2,3,4,5,6];
>> h = a ./ (sum(a) - a)
h =
0.050000 0.105263 0.166667 0.235294 0.312500 0.400000

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Tags

Aucun tag saisi pour le moment.

Community Treasure Hunt

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

Start Hunting!

Translated by