How do you put in a range of values into a variable of a matrix?
조회 수: 5 (최근 30일)
이전 댓글 표시
I have a simple question. How do you put in a range of values into a variable of a matrix? I tried doing this code below:
ho2 = linspace(5,50,51);
A2 = [-35 30 0 0 0; 30 -30.32 .32 0 0; 0 .32 -2.82 2.5 0; 0 0 2.5 -16.5 14; 0 0 0 14 (14+ho2)]
The error I keep receiving is:
Error using vertcat Dimensions of matrices being concatenated are not consistent.
Error in Untitled3 (line 3) A2 = [-35 30 0 0 0; 30 -30.32 .32 0 0; 0 .32 -2.82 2.5 0; 0 0 2.5 -16.5 14; 0 0 0 14 (14+ho2)]
댓글 수: 0
채택된 답변
Stephen23
2014년 12월 2일
편집: Stephen23
2014년 12월 2일
The matrix A2 has size 5x5 (excluding the last element), into one element of which you are trying to place the variable ho2, which has size 1x51. In MATLAB, an element of a numeric array is a single scalar value. But is this instance, you are trying to place 51 values into it...
Thus the error is telling you this: "You cannot put something with multiple values into a space that can only fit one value!"
By the looks of your code, you need to reconsider what you are trying to define as the last element of A2. If you replace the last element with a simple scalar numeric, then it works fine without any error.
댓글 수: 11
Stephen23
2014년 12월 3일
편집: Stephen23
2014년 12월 3일
The line Q2 = ho2; performs array preallocation. MATLAB dynamically allocates memory as arrays grow bigger, which is very convenient, but this process can slow down code if the arrays grow many times or in large steps. Every time it grows, MATLAB has to check if it fits the current memory space allocated, and if not, it copies it to a new area of memory. It can be faster to preallocate an array to the size that it will need to be, before starting to work with it, which is what I did here by defining the output array to be the same size as one of the input arrays (otherwise it would grow fifty times in the for-loop).
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!