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 CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by