MATLAB Answers

Translated by

このページのコンテンツは英語から自動翻訳されています。自動翻訳をオフにする場合は「<a class="turn_off_mt" href="#">ここ</a>」をクリックしてください。


Can looping values be used for indexing?

さんによって質問されました 2019 年 3 月 26 日
最新アクティビティ Stephen
さんによって コメントされました 2019 年 3 月 26 日
Hello, I have a variation of the following code running but I am looking to make the code a bit more efficient by looping instead of defining a unique variable each time.
LPCsale = zeros(3,19);
finalpop = [5000,1,5000,0,5000,1];
LLPmatrix = finalpop(:,2:2:end);
LPClim= 20000;
LPCcost = 100000;
for LPCloop = 1:3
LPCsale(LLPmatrix(:,LPCloop)) = round(((LPClim-(finalpop(LLPmatrix(:,LPCloop),1)))/LPClim)*LPCcost)-LPCcost;
In the working code there are LPCsale1, LPCsale2 and LPCsale3 variables. The LPCloop value is replaced by 1,2, and 3 instead.
Is it possible to use a looping value like this to perform indexing? I am receiving this error message curently:
"Index in position 1 is invalid. Array indices must be positive integers or logical values"
I will need to expand the number of LPCsale values further so I would like a more efficient way to do this than having blocks and blocks of similar code.
Appreciate any advice!

  0 件のコメント

サインイン to comment.




1 件の回答

回答者: James Tursa
2019 年 3 月 26 日
編集済み: James Tursa
2019 年 3 月 26 日

finalpop, and thus LLPmatrix, has a 0 value as one of its elements. You then use this as an index within the loop, which is causing the error.

  3 件のコメント

2019 年 3 月 26 日
Hi James, thanks for the answer. Struggling a little bit to follow (i think ive been staring at this too long). If you don't mind clarifying further that would be great.
In the working code, this is setup to return the values in finalpop which correspond to those cells in LLPmatrix where the value is 1, and ignore those set to 0. It is dependent on having either a zero or 1 in finalpop and LLPmatrix.
I don't quite see how I'm using that zero value as an index within the loop, could you elaborate? Is this just not possible to do if I have to have zeros in finalpop/LLPmatrix?
James Tursa
2019 年 3 月 26 日
When I just copy and paste your code into MATLAB I get this error:
Index in position 1 is invalid. Array indices must be positive integers or logical values.
Then look at the current value of this expression, which you are using as an index:
>> LLPmatrix(:,LPCloop)
ans =
In fact, if you just look at the entire LLPmatrix you can see that it has a 0 element which will eventually cause the indexing error:
>> LLPmatrix
LLPmatrix =
1 0 1
2019 年 3 月 26 日
Ah my apologies I see now. Thanks for the help!

サインイン to comment.

Translated by