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

2 views (last 30 days)
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 Comments
Guillaume
Guillaume on 27 Aug 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.

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 27 Aug 2015
Edited: Stephen23 on 27 Aug 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

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Tags

No tags entered yet.

Community Treasure Hunt

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

Start Hunting!