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

2 Ansichten (letzte 30 Tage)
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 Kommentare
Guillaume
Guillaume am 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.
Hind Albasry
Hind Albasry am 28 Aug. 2015
You are absolutely right . Thank you for the explanation , appreciate that :)

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Stephen23
Stephen23 am 27 Aug. 2015
Bearbeitet: Stephen23 am 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

Weitere Antworten (0)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Tags

Noch keine Tags eingegeben.

Community Treasure Hunt

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

Start Hunting!

Translated by