What are these lines doing? (Matlab) - matlab

I am trying to translate a small program from MATLAB to Python. I do not have MATLAB to run the code and see the output. Anyways, the program has a weird section that I do not know how to interpret correctly.
Here is that part of the code:
randn('state',2)
for ncase=1:3
sumex=0;
I know randn gives a matrix with normally distributed numbers - but what does it have to do with the for loop - and 'state'? I notice there is no semicolon after it.
I am guessing 'state' is the name of the matrix, and it is not initiated - nor referenced anywhere else in the code.
If I commented out randn('state',2) is it going to change the output?

Commenting out randn('state',2) will have an effect on the code and its output as randn('state',2) is old discouraged MATLAB syntax to specify the random number generator to use with randn and to seed it.
You could replace it simply with your own method to seed your own random number generator of choice in python.
for ncase=1:3 will loop from 1 to 3 in increments of 1. ncase will be 1 in the first iteration, 2 in the second iteration and 3 in the third and final iteration.
sumex=0; sets the variable sumex equal to 0.

Related

behavior of matlab's rng() function in loop

With rng() before for loop Matlab generate one array of random number, within for loop another one. Both results are repeatable, so rng() seeds work. But I want to know the reason of such behavior.I was expecting the results to be same. I think actually it is not because of rng but for loop
Code exapmle?
for i = 1:2
rng(1,'philox');
disp(randn(2,1)); % 1st number is 0.0906, 2nd one is -0.7327
end
rng(1,'philox');
for i = 1:2
disp(randn(2,1)); % 1st number is 0.7565, 2nd one is -0.7096
end
Shouldn't the results be same? Isn't rng(1,..) storing same array of numbers for seed 1
Your code works as you expect and would describe, I believe. You are definitely not showing in your code example all the outputs. This is what I get when running it.
>> test
First case:
0.0906
-0.7327
0.0906
-0.7327
Second case:
0.0906
-0.7327
0.7565
-0.7096
In the first case, you reset the random number generator inside the loop, and there fore you get twice the same results (two numbers). In the second case, you only set it once, and therefore you get the same numbers as before, and then the second loop you get the next 2 corresponding random numbers produced by the algorithm. These algorithms, once started, will produce an infinite amount of different numbers, and they won't produce the same unless you explicitly call the restart of the algorithm with the seed, like you do in the first example.
All this is way less confusing if you call disp(randn(1)) inside the loop, instead of generating 2 numbers each time.

Random Number Generator is repetitive in simulink

How does one ensure that a model in the form of simulink generated executable "standalone executable" generate different random sequence every time the executable is executed.
I added rng('shuffle') in the initFcn Callbacks, but that didn't do the trick.
I think I found your solution - the rand function always generates the same numbers every time MATLAB is loaded (it gets initialized with a 0 seed). That's why you get different outputs (re)running from MATLAB than when the exe is built. The workaround is to add this line to your code (which will instead generate a random seed based on the system clock) ONLY ONCE IN YOUR CODE before your calls to rand, randn, or randi:
%THIS IS THE SOLUTION GIVEN FOR AN EXE (UPDATED FOR NEWER MATLAB VERSIONS)
reset(RandStream.getGlobalStream,sum(100*clock))
%OR (THIS IS INSIDE MATLAB, HAVEN'T TRIED WITH AN EXE)
RandStream.setGlobalStream(RandStream('mt19937ar','seed',sum(100*clock))); %note you can use 6 other random number generators, type RandStream.list for more
See here for more details: https://www.mathworks.com/matlabcentral/answers/104306-why-does-my-compiled-rand-function-give-the-same-values-every-time-i-run-my-matlab-generated-standal
https://www.mathworks.com/matlabcentral/answers/336-why-do-i-get-the-same-numbers-in-randn-function?s_tid=answers_rc1-1_p1_Topic
Now if you're using MATLAB coder you're supposed to do something like this (if clock isn't available):
coder.cinclude('"time.h"')
sd=0;
sd=coder.ceval('time',[]);
rng(sd);
All of these solutions work on the rand, randn, randi functions.

Simulink with if/else and different signal dimension

I need to implement a if/else in simulink to find out if a input is a scalar value or a matrix. Please see, the diagram below :
Given:
Block(1) - is a input that can be a scalar "1" or a matrix "[[0 15];[5 10]]"
Block(2) - must return the signal dimension of the input. Ex: 1 for scalar and >1 for a matrix
The requirements are:
Everything must work interpreted or compiled (Simulink coder)
The final output of blocks (4) and (5) are scalars
I have average understanding of CMexSFunctions. So if I need to implement one to solve the problem it is ok
So far, I have had the following problems:
I don't at all if what I am planning to do is feasible
I don't know how to implement Block(2) to work on compiled mode
Even though there is a if/else, simulink performs a pre-check before running to verify if all signal dimensions are ok. During this check, it gives a error saying ex: that Block(5) has a input of matrix
Any Clues?
Block(2) is the easiest part which can be implemented using the "Probe" block in Simulink library. Your Input at port 1 must be variable sized signal since you are expecting a scalar or matrix.
I assume you are feeding Input(1) to blocks 4 and 5. At model compile time Simulink does not know which one of these blocks are going to run based on the input size. So Simulink needs to assume both blocks may get scalar or matrix. You need to make blocks 4 and 5 not throw error for both scalar and matrix even though they will be used only for one type at run-time.
If you are not able to do this, for the scalar case a simple work around is to place a Selector before block 5 that selects the first sample always. This will let Simulink know that the input to block 5 is always a scalar.

In Matlab code, (X~=1).*Y. How to stop executing Y when x~=1 fails?

I'm writing a piece of code for my thesis and comes to the following problem.
In creating ksubgrid, if the first logical part fails, e.g. there are elements in reshape(kmax_ind,nz*nb*nk*nxi,1) equals to 1, MATLAB reports an error since the first vector in linspaceNDim has a vector with column number 0.
How do I let MATLAB stop doing linspaceNDim when the logical fails? I know that if I do an element-by-element loop, the if statement can solve the problem. But since number of loops is large here, it's gonna be slow.
So how to solve the problem in matrix?
ksubgrid=reshape((reshape(kmax_ind,nz*nb*nk*nxi,1)<nk & reshape(kmax_ind,nz*nb*nk*nxi,1)>1 ).*...
linspaceNDim(kgrid(1,reshape(kmax_ind,nz*nb*nk*nxi,1)-1),kgrid(1,reshape(kmax_ind,nz*nb*nk*nxi,1)+1),nksub)

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.