Iterate through an excel file and perform vector operations

2 次查看(过去 30 天)
I am trying to iterate through an excel file and apply an equation involving subtracting a vector made from the excel file and a constant vector. I am fairly new to MATLAB and have an idea but would like to be pointed in the right track. I was thinking of using a for loop but not sure on the syntax. Any help would be appreciated.
  3 个评论
dpb
dpb 2014-10-14
doc xlsread % get the data
After that you likely do not need any loops. Have you worked thru the beginning examples in the "Getting Started" section of the online documentation to see how matrix operations work in Matlab?
ImageMan
ImageMan 2014-10-14
I have an I have imported the excel file into matlab and the x,y,z locations are in there own separate matrices I just need to apply the equation to all positions and sum them up. For example, the observer is located at 1x-3y+4z and a point charge is located 3x-5y+3z. I know to get that I would just do the x(observer)-x(pointcharge) y(observer)-y(pointcharge) and so forth but would that only give me one position? Also how would I find the magnitude of this vector? I can attach the files if that makes it easier.

请先登录,再进行评论。

采纳的回答

dpb
dpb 2014-10-14
编辑:dpb 2014-10-15
That's ok (altho I'd probably not use separate variable but an array).
If the arrays are x, y, z and the constant point is px, etc., ...
>> x=1;y=-3;z=4;px=3;py=5;pz=3;
>> dx=bsxfun(@minus,x,px);
dy=bsxfun(@minus,y,py);
dz=bsxfun(@minus,z,pz);
>> r=sqrt(dx.^2+dy.^2+dpz).^2)
r =
8.3066
>>
As noted you could reduce the number of equations by working with the positions as an array and a vector instead of separate operations...
d=[x y z].-repmat([px py pz],length(x),1);
r=sqrt(sum(d.^2,2));
Now the three columns of d are x,y,z, respectively, of course and r is still a vector.
ADDENDUM
With the understanding that Q is same size as r, then the summation of the formula is simply
res=sum(Q./(4*pi*epsilon*r));
so the whole solution looks like
d=[x y z].-repmat([px py pz],length(x),1);
r=sqrt(sum(d.^2,2));
res=sum(Q./(4*pi*epsilon*r));
which is why I asked initially if you had worked thru "Getting Started" section where it illustrates array operations and the "dot" operators and the like...
If you still hadn't I commend it to your attention sooner rather than later.
  7 个评论
ImageMan
ImageMan 2014-10-15
编辑:dpb 2014-10-15
I got it
answer=zeros(1,10);
for i=1:length(Q)
v=Q(i)/(4*pi*epsilon*r(i));
answer(i)=v;
end
answer=sum(answer)
dpb
dpb 2014-10-15
Oh, so there's a Q for each r? Somehow I go the idea they were two separate things. That point was what I was trying to clarify.
See the updated Answer for "the Matlab way"...

请先登录,再进行评论。

更多回答(0 个)

产品

Community Treasure Hunt

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

Start Hunting!

Translated by