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

2 ビュー (過去 30 日間)
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 件のコメント
Guillaume
Guillaume 2015 年 8 月 27 日
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 2015 年 8 月 28 日
You are absolutely right . Thank you for the explanation , appreciate that :)

サインインしてコメントする。

採用された回答

Stephen23
Stephen23 2015 年 8 月 27 日
編集済み: Stephen23 2015 年 8 月 27 日
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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

タグが未入力です。

Community Treasure Hunt

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

Start Hunting!

Translated by