How to use root function inside for loop?

8 ビュー (過去 30 日間)
Antoine van Hirtum
Antoine van Hirtum 2017 年 8 月 11 日
回答済み: Antoine van Hirtum 2018 年 1 月 2 日
I would like to use a for loop to perform the roots command for a cubic function for a range of theta's and phi's and volumes. Then the three-dimensional matrix C should contain all the possible roots from each given entry of theta and phi. I have 7 values for theta, 7 for phi and 5 for volume. The theta and volume are stored along one 'direction' of the C matrix, the phi's along another 'direction' of the C matrix and the roots in the third direction of C. The error I receive is "Subscripted assignment dimension mismatch". and "Assignment has more non-singleton rhs dimensions than non-singleton subscripts" Does anyone have an answer (other options for solving the problem are also welcome)? The code is attached.
Thanks in advance, Antoine
  2 件のコメント
Jan
Jan 2017 年 8 月 11 日
Please post the complete error message, such that we do not have to guess, in which line the error occurs. How can you get 2 error messages? Matlab stops after the first problem already.
Antoine van Hirtum
Antoine van Hirtum 2017 年 8 月 11 日
編集済み: Geoff Hayes 2017 年 8 月 12 日
Assignment has more non-singleton rhs dimensions than non-singleton subscripts
Error in bubble_matlab (line 15)
C(k+5*(i-1),j)=roots([r3(i,j) r2(i,j) r1(i,j) -Volumes(k)]);

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

回答 (2 件)

Jan
Jan 2017 年 8 月 12 日
編集済み: Jan 2017 年 8 月 12 日
C(k+5*(i-1),j) is a scalar, but roots([r3(i,j) r2(i,j) r1(i,j) -Volumes(k)]) can be a vector. The error message tells you, that the number of elements on the left and on the right differ. Do you mean:
C(k+5*(i-1), j, :)
% ^ 3rd dimension
or
r = roots([r3(i,j), r2(i,j), r1(i,j), -Volumes(k)]);
C(k+5*(i-1), j, 1:numel(r)) = r;
if there are not 3 roots in all cases. Perhaps you want a cell array instead:
C = cell(7*5,7);
...
C{k+5*(i-1), j} = roots([r3(i,j), r2(i,j), r1(i,j), -Volumes(k)]);
Note: Using commas to separate elements of a vector is safer to reduce ambiguities.

Antoine van Hirtum
Antoine van Hirtum 2018 年 1 月 2 日
Thanks for your answer. In order to solve the problem I simplified my code and added comments to clarify. I have used the roots function to solve the equation F1(theta,dP,Rcav,R1)=F2(theta,dP,Rcav,R2) for R2. I would like to use a for loop to calculate this equation for a range of variables: theta's, dP's and Rcav's. This time the for loop does not produce an error. However, the resulting calculated radii (R2 substituted back into equation F2) does not yield the desired result F1. Or in other words, the outcome of roots does not seem correct.
Any help is welcome. Thanks in advance.

カテゴリ

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