Hello,
I am trying to make a for loop to create inputs for a function, and store outputs - there are 4 inputs, and manually I would type in:
ones(4,1) in the function which is called main, so it looks in the input window as: main(ones(4,1))
This gives 4 outputs, which I would like to store in an excel file later on. However, I want to vary these inputs, and change all 4 of them to make 4^4 combinations (256) with two numbers (1 or 5). So for example:
[1 1 1 1];
[5 1 1 1];
[1 5 1 1];
[5 5 1 1];
[1 1 5 1]; ...................
as you can see, doing this manually is quite tedious - I know a for loop helps here and I can make 256 iterations run by
for i = 1:256
(this is main body)
.....
end
I am confused on whether I should have a nested loop to do this, and how I can store these values in separate rows for each iteration. Any help will be appreciated.

 Akzeptierte Antwort

David Hill
David Hill am 2 Dez. 2022

0 Stimmen

r=randi(2,5,4);
r(r==2)=5
r = 5×4
1 1 5 5 1 1 5 1 5 1 1 1 1 5 1 5 1 1 5 5

4 Kommentare

Pool
Pool am 2 Dez. 2022
Thanks for the response - so are you saying that using the randi function, I can generate a matrix of all 256 combinations? I think this works if all the possibilties are stated - I guess my follow up question will be on how I should extract the results for each input?
I am confused when you say 256 combinations. Are there not only 2^4 (16) combinations? I guess I don't understand your question.
R =[ 1 1 1 1
1 1 1 5
1 1 5 1
1 1 5 5
1 5 1 1
1 5 1 5
1 5 5 1
1 5 5 5
5 1 1 1
5 1 1 5
5 1 5 1
5 1 5 5
5 5 1 1
5 5 1 5
5 5 5 1
5 5 5 5];
r=randi(16,4,1)
r = 4×1
7 9 11 15
A=R(r,:)
A = 4×4
1 5 5 1 5 1 1 1 5 1 5 1 5 5 5 1
Pool
Pool am 3 Dez. 2022
You are right, sorry for the confusion haha - so if I was running a for loop for i = 1:16 iterations, and I get an output from another function, which gives out a 1x4 vector = [x1 x2 x3 x4] - and I want to store these into an empty matrix (zeros(16,4)), would I write:
for i = 1:16
s = (zeros(16,4));
r=randi(2,16,4);
r(r==2)=5;
x = main(r(i,:));
s(i,:) = x(1,:);
end
For some reason, this does not store the 1x4 outputs for me and gives an error
s=zeros(16,4);
for i=1:16
r=randi(2,1,4);%assumed output from another function
r(r==2)=5;
s(i,:)=r;
end
s
s = 16×4
1 1 1 5 5 5 5 5 1 1 1 5 1 1 1 5 1 5 1 1 1 5 5 1 5 5 5 5 1 1 5 5 1 1 1 1 5 5 5 1

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Produkte

Version

R2022b

Gefragt:

am 1 Dez. 2022

Kommentiert:

am 3 Dez. 2022

Community Treasure Hunt

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

Start Hunting!

Translated by