How do you put in a range of values into a variable of a matrix?

2 views (last 30 days)
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)]

Accepted Answer

Stephen23
Stephen23 on 2 Dec 2014
Edited: Stephen23 on 2 Dec 2014
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 Comments
Yianni
Yianni on 3 Dec 2014
To answer your question, yes it was intentional because I am only using one value in the matrix to solve for Q2. Out of curiosity, is the line below needed?
Q2 = ho2;
I removed it and got the same output in the plot and for the values of each variable.
Stephen23
Stephen23 on 3 Dec 2014
Edited: Stephen23 on 3 Dec 2014
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).

Sign in to comment.

More Answers (0)

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!