Extract every second value of a vector and write into a new vector

7 ビュー (過去 30 日間)
Grillteller
Grillteller 2017 年 2 月 3 日
編集済み: Grillteller 2017 年 2 月 6 日
Hi, another trivial question i guess - i'm a beginner at Matlab.
MATLAB code
Xi = sym('Xi',[1,n2]);
for i=1:1:6
BGx(i,1)=L1*Xi(i);
BGy(i,1)=L5*Xi(i);
end
I want to write the results into a new vector. I tried vertcat and some for loops but it didn't work out.
MATLAB code
BG=vertcat(BGx; BGy);
Here i get a result like (L1*Xi1, L1*Xi2, L1*Xi3, ...., L5*Xi1, ...., L5*Xi6) but i want to get (L1*Xi1, L5*Xi1, L1*Xi2, L5*Xi2, ...., L5*Xi6). Is there a trick when using vertcat or do i need to write a loop. I have the problem that BG has another dimension than the 2 vectors BGx and BGy. Thanks in advance
  3 件のコメント
Grillteller
Grillteller 2017 年 2 月 6 日
Hi Stephen, i need to set up a lot of terms with undefined variables (the term is longer than the example) and in a next step i have to differentiate the terms. After this step i substitute the variables with numbers. Perhaps there is a better way...
Stephen23
Stephen23 2017 年 2 月 6 日
@Grillteller: if you need mathematically exact algebraic outputs then sym is fine. If you are doing calculations with numbers then a numeric solution might do the job, and be faster and simpler to code than using sym. For example it is easy to use gradient, or fit a spline and differentiate that.

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

採用された回答

Niels
Niels 2017 年 2 月 3 日
result = zeros(12,0);
for i=1:1:6
result((i-1)*2+1)=BGx(i,1);
result(i*2)=BGy(i,1);
end
  1 件のコメント
Grillteller
Grillteller 2017 年 2 月 6 日
編集済み: Grillteller 2017 年 2 月 6 日
When i try this, i get an error code:
The following error occurred converting from sym to double: DOUBLE cannot convert the input expression into a double array.
Edit: I found the solution - A "sym" was missing before "zeros".
result = sym(zeros(12,0));
for i=1:1:6
result((i-1)*2+1)=BGx(i,1);
result(i*2)=BGy(i,1);
end

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

その他の回答 (1 件)

Stephen23
Stephen23 2017 年 2 月 3 日
編集済み: Stephen23 2017 年 2 月 3 日
This is MATLAB so why use an ugly loop? MATLAB is much better than that! The code is simpler without it (I also got rid of sym: you don't say why you need it, and numeric operations will be much faster and more efficient):
>> X = [1,2,3,4];
>> L1 = 90;
>> L5 = 10;
>> Z = [L1+X;L5+X];
>> Z = Z(:)'
Z =
91 11 92 12 93 13 94 14

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by