MATLAB struct conversion error - matlab

I have 5 different structure and I want to calculate some variables for all of them. To do that, I wrote the following code:
for i=1:5
[StructureI(i), ReqTab(i), jt(i), B(i)]=Checkall(E);
end
The values StructureI, ReqTab, jt and B are calculated in another function and they are
StructureI= 1X4 matrix,
ReqTab= 4X2 matrix,
jt=2x1 matrix,
B=4x4 matrix
When I run the code it calculates all the varibles in the function Checkall. However, when it turns to the parent code, it gives and error "Conversion to double from struct is not possible."
How can I solve this problem?
Thanks in advance.

You cannot assign directly from double to struct, instead you have to write the specific field field_name to assign to:
[StructureI(i).field_name, ReqTab(i), jt(i), B(i)] = Checkall(E);
If all of these variables (i.e. also ReqTab, jt, B) are structures, then off course you need to specify the field in each one of them, using the . notation.
However, as mentioned in the comments, all iterations of your loop are just the same (no usage of i within it), so why do you need this loop? just to make 5 copies?

Related

Load an do operations with a matrix whose name varies within a Matlab loop

I have to run a Matlab loop indexed by x. At each iteration, I have to load and work with an array, A_x.mat, where the subscript x follows the loop index. How can I do that? Let me give you and example to highlight my issue. The example is very silly but serves my purposes.
X=10;
C=cell(X,1)
for x=1:X
load(['A_' num2str(x) '.mat']); %here I load A_x.mat
%C{x}=A_x*3;
end
I don't know how to compute A_x*3 in a way that allows the subscript x to vary. Could you advise?
To solve my issue I also tried
for x=1:X
B=load(['A_' num2str(x) '.mat']); %here I load A_x.mat and "rename" it B
%C{x}=B*3;
end
but B turns out to be a 1x1 struct with 1 field that is again A_x. Hence, I have not solved anything.
You can save the structure subfield name as a char and access the structure with it directly:
X=10;
C=cell(X,1)
for x=1:X
name = ['A_', num2str(x)];
data_structure = load([name, '.mat']); %here I load A_x.mat
C{x} = data_structure.(name) * 3;
end
Note that you could achieve something similar with eval() but that is not recommended. If ever you need to access variables dynamically like this, use a structure.

Creating functions in Matlab

Hi, I am trying to write a function as per the question. I have tried to create four sub-matrices which are the reverse of each other and then multiply to give the products demanded by the question. My attempt:
function T = custom_blocksT(n,m)
T(1:end,end-1:1);
T(1:end,end:-1:1)*2;
T(1:end,end:-1:1)*3;
T(1:end,end:-1:1)*4;
What I'm unsure of is
(i) What do the the indivual sub-matrices(T(1:end,end-1:1);)need to be equal to? I was thinking of(1:3)?
(ii) I tried to create a generic sub-matrix which can take any size matrix input using end was this correct or can't you do that? I keep getting this error
Undefined function or variable 'T'.
Error in custom_blocksT (line 2)
T(1:end,end-1:1);
I have searched the Matlab documentation and stacked overflow, but the problem is I'm not quite sure what I'm supposed to be looking for in terms of solving this question.
If someone could help me I would be very thankfull.
There are many problems with your function:
function T = custom_blocksT(n,m)
T(1:end,end-1:1);
T(1:end,end:-1:1)*2;
T(1:end,end:-1:1)*3;
T(1:end,end:-1:1)*4;
end
This is an extremely basic question, I highly recommend you find and work through some very basic MATLAB tutorials before continuing, even before reading this answer to be honest.
That said here is what you should have done and a bit of what you did wrong:
First, you are getting the error that T dos not exist because it doesn't. The only variables that exist in your function are those that you create in the function or those that are passed in as parameters. You should have passed in T as a parameter, but instead you passed in n and m which you don't use.
In the question, they call the function using the example:
custom_blocks([1:3;3:-1:1])
So you can see that they are only passing in one variable, your function takes two and that's already a problem. The one variable is the matrix, not it's dimensions. And the matrix they are passing in is [1:3;3:-1:1] which if you type in the command line you will see gives you
[1 2 3
3 2 1]
So for your first line to take in one argument which is that matrix it should rather read
function TOut = custom_blocks(TIn)
Now what they are asking you to do is create a matrix, TOut, which is just different multiples of TIn concatenated.
What you've done with say TIn(1:end,end-1:1)*2; is just ask MATLAB to multiple TIn by 2 (that's the only correct bit) but then do nothing with it. Furthermore, indexing the rows by 1:end will do what you want (i.e. request all the rows) but in MATLAB you can actually just use : for that. Indexing the columns by end-1:1 will also call all the columns, but in reverse order. So in effect you are flipping your matrix left-to-right which I'm sure is not what you wanted. So you could have just written TIn(:,:) but since that's just requesting the entire matrix unchanged you could actually just write TIn.
So now to multiply and concatenate (i.e. stick together) you do this
TOut = [TIn, TIn*2; TIn*3, TIn*4]
The [] is like a concatenate operation where , is for horizontal and ; is for vertical concatenation.
Putting it all together:
function TOut = custom_blocks(TIn)
TOut = [TIn, TIn*2; TIn*3, TIn*4];
end

Subscripted assignment dimension mismatch

here is the code listing and i got the above mentiond error at line nests(r,c)=nests(r,c)+stepsize.*randn(size(nests(r,c))); please let me now what is wrong with my code as i m new to matlab
for r = 1:numb_of_nest % for each particle
for c = 1:4
u=randn(size(nests(r,c)))*sigma;
v=randn(size(nests(r,c)));
step=u./abs(v).^(1/beta);
nests(r,c)=nests(r,c)+stepsize.*randn(size(nests(r,c)));
% Apply simple bounds/limits
ns_tmp=nests(r,c);
I=ns_tmp<Lb(c);
ns_tmp(I)=Lb(I);
% Apply the upper bounds
J=ns_tmp>Ub(c);
ns_tmp(J)=Ub(J);
% Update this new move
nests(r,c)=ns_tmp;
end
end
This error happens when you assign a value of some dimension m x n to a subscripted variable of different dimension.
In your case, assuming nests has no third dimension, you're assigning to a scalar (1x1) variable. This only works if the value you're trying to assign also is a scalar. Since you get the error, it probably isn't. The only place where your dimensions can be non-scalar is stepsize, so to fix this error, make sure stepsize is a scalar value.
According to the definition you gave in an earlier comment (stepsize=0.01*step.*(nests(r,c)-best);), this problem translates to make sure best is a scalar value. Possibly by subscripting, I can't tell you exactly how since I don't know what best is.
step=u./abs(v).^(1/beta);
nests(r,c)=nests(r,c)+stepsize.*randn(size(nests(r,c)));
Here you're assigning a value to the variable step, but then using a different variable called stepsize that hasn't been assigned a value anywhere in this code. Is this intentional? If not, stepsize is probably some leftover variable from previous code which is messing up the dimensions and giving you this error.
In addition to the above, is nests an ordinary two-dimensional matrix in your code? If so, taking size(nests(r,c)) every time is unnecessary - since you're giving two subscripts, the result is only going to be 1 all the time. Or is nests a cell array perhaps? In that case, you might want to index using curly braces { } instead of ordinary parantheses, to get the size of the matrix that's sitting inside the cell.

Passing Struct elements of variable lengths into a matrix Matlab

I am parshing a few data via the internet. The struct Data has several elements. I am interested in Data.Value a call of Data(1,1).Value is a double vector of [56,1]. Moving on to the second struct cell Data(1,2).Value is a double vector [46,1].
Writing a FOR Loop to get the entire Data(1,i).Value from 1 to 500, when it come to the second element, I get the following error returned: Subscripted assignment dimension mismatch.
Although I understand the error I cannot justify it and hence I cannot work out a solution.
I have also tried to pre-define a matrix of variable sizes to overcome this, without result.
Anybody can think of any solution to get the entire Data(1,:).Value
Thanks a lot for the contribution guys.
You can use
vertcat(Data(1,:).Value)
to create a column vector made by concatenating Data(1,1).Value, Data(1,2).Value, ...
Alternatively, you can use the generalized concatenation operator
cat(1, Data(1,:).Value)

Concatenate equivalent in MATLAB for a single value

I am trying to use MATLAB in order to generate a variable whose elements are either 0 or 1. I want to define this variable using some kind of concatenation (equivalent of Java string append) so that I can add as many 0's and 1's according to some upper limit.
I can only think of using a for loop to append values to an existing variable. Something like
variable=1;
for i=1:N
if ( i%2==0)
variable = variable.append('0')
else
variable = variable.append('1')
i=i+1;
end
Is there a better way to do this?
In MATLAB, you can almost always avoid a loop by treating arrays in a vectorized way.
The result of pseudo-code you provided can be obtained in a single line as:
variable = mod((1:N),2);
The above line generates a row vector [1,2,...,N] (with the code (1:N), use (1:N)' if you need a column vector) and the mod function (as most MATLAB functions) is applied to each element when it receives an array.
That's not valid Matlab code:
The % indicates the start of a comment, hence introducing a syntax error.
There is no append method (at least not for arrays).
Theres no need to increment the index in a for loop.
Aside of that it's a bad idea to have Matlab "grow" variables, as memory needs to be reallocated at each time, slowing it down considerably. The correct approach is:
variable=zeros(N,1);
for i=1:N
variable(i)=mod(i,2);
end
If you really do want to grow variables (some times it is inevitable) you can use this:
variable=[variable;1];
Use ; for appending rows, use , for appending columns (does the same as vertcat and horzcat). Use cat if you have more than 2 dimensions in your array.