Here are the script and the mat. file
What I wanna do is if I run the script file,and type 1 and 600 as a input I got
I got three ans but only last one ans = 0.2515 is stored as a variable I need to store 'ans' as
ans =
- 0.4992
0.3636
0.2515
how can I do this?

4 件のコメント

KSSV
KSSV 2018 年 8 月 14 日
Error while running the script:
Undefined function or variable 'magvector'.
YOur code need to be refined a lot. No initialization, you need to initialize the arrays before loops.
Yunseo Choi
Yunseo Choi 2018 年 8 月 14 日
function Rmag = magvector(r)
Rmag=sqrt(r(1)^2+r(2)^2+r(3)^2);
Yunseo Choi
Yunseo Choi 2018 年 8 月 14 日
Sorry I cannot attach the file anymore
Stephen23
Stephen23 2018 年 8 月 14 日
編集済み: Stephen23 2018 年 8 月 14 日
Or even better, get rid of the loops entirely. Most of them are waste of time, as vectorized code is simpler. The first two loops can be replaced by these two lines:
diffe = diff(A);
subbond = (diffe(1:end-1,:)+diffe(2:end,:))/2;
Possibly the rest of the code could be simplified as well, but until we have magvector we can't do much more.

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

 採用された回答

Jan
Jan 2018 年 8 月 14 日
編集済み: Jan 2018 年 8 月 14 日

1 投票

Either:
result = nan(598, size(sbz, 2)); % Pre-allocate
count = 0;
for n = 1:598
if c(1)<=position2(n,1)&&c(2)>=position2(n,1)
count = count + 1;
result(count, :) = sbz(n,:)
end
end
result = result(1:count, :); % Crop unneeded memory
or more efficient with logical indexing:
index = (c(1) <= position2(:,1) & c(2) >= position2(:,1));
result = sbz(index, :);
Note: Do not use "ans" directly, because it is very volatile. Assign the values to a variable explicitly instead.

その他の回答 (1 件)

Stephen23
Stephen23 2018 年 8 月 14 日
編集済み: Stephen23 2018 年 8 月 14 日

1 投票

Get rid of the most of the loops, they don't help you. Learn how to write vectorized code. Here is your code, simplified:
magvector = @(r) sqrt(r(1).^2+r(2).^2+r(3).^2);
%
S = load('position2.mat');
%
diffe = diff(S.position2); % 1st loop
subbond = (diffe(1:end-1,:)+diffe(2:end,:))/2; % 2nd loop
%
for j = size(diffe,1)-1:-1:1
sbz(j,:) = (3*((dot(subbond(j,:), [1,0,0])/magvector(subbond(j,:)))^2)-1)/2;
end
%
c = linspace(min(S.position2(:,1)),max(S.position2(:,1))+0.0001,1*ceil(max(S.position2(:,1))-min(S.position2(:,1))));
%
idx = c(1)<=S.position2(:,1) & c(2)>=S.position2(:,1); % 4th loop
out = sbz(idx,:)
Giving:
out =
-0.49921
0.36363
0.25148

1 件のコメント

Yunseo Choi
Yunseo Choi 2018 年 8 月 14 日
thank you so much!

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

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

質問済み:

2018 年 8 月 14 日

コメント済み:

2018 年 8 月 14 日

Community Treasure Hunt

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

Start Hunting!

Translated by