How do you put in a range of values into a variable of a matrix?
2 次查看(过去 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 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!