Outputting multiple matrix of a function within a for loop?
조회 수: 3 (최근 30일)
이전 댓글 표시
Hello, I'm really desperate when trying to evaluate this function n times within a for loop, I might be making a mistake that I can't see. I would be grateful if you help me.
I have this function:
function F = A(T,a)
The output of F if it's evaluated for each value of T and a is a matrix 6x3.
I did this to create the for loop and get n expressions of the matrix 6x3:
for n = (0:size(T)-1)'
F(n+1) = A(T(n+1,:),a);
end
F should be an array of n6x3 matrices, but I get an output of 1 matrix 6x3, and it's not within the n elements. I also tried to create structs or cells arrays but I always got the same output.
There's no problem with the function because I evaluted it without the for loop like this:
F(1) = A(T(1,:),a);
F(2) = A(T(2,:),a);
F(3) = A(T(3,:),a);
.
.
.
and it gave me the correct results per individual iteration, but it's not efficient...
I hope you could understand what I'm trying to say, english is not my first language =( I hope you can help me with this, thanks in advance! =)
댓글 수: 0
답변 (2개)
Stephen23
2017년 11월 17일
편집: Stephen23
2017년 11월 17일
Solution: The problem is caused by the transpose operation:
for n = (0:size(T)-1)'
^ this causes the problem!
Remove the transpose.
Explanation: Why does this happen? Because FOR actually keeps columns together, its help clearly states that when the input is an array it will: "Create a column vector, index, from subsequent columns of array valArray on each iteration". You provided an array, hence got columns. You can see the difference by trying these:
>> for k = (0:3)', size(k), end % transpose, what you do now
ans =
4 1
>> for k = 0:3, size(k), end % what you should be doing
ans =
1 1
ans =
1 1
ans =
1 1
ans =
1 1
You could have solved this yourself by reading the MATLAB documentation. This is why we recommend that users read the documentation for every function and operator that they use, no matter how trivial they think it is. Then they easily avoid pointless bugs like this.
댓글 수: 2
Matt J
2017년 11월 18일
Stephen isn't wrong. The transpose is definitely one of your problems. However, you have an additional problem, namely that you are trying to send a 6x3 matrix to a scalar address F(n+1). My answer deals with that.
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!