MATLAB Answers

Understanding data structures.

2 views (last 30 days)
Alex on 8 Mar 2012
Hey all, I have a question about the data Matlab is presenting me with.
When I run a program I have created, Matlab outputs the solutions in a .csv file, which is convenient, but it may be causing me some trouble. When I run the program and ask matlab to present me with soln (see below) I get a [425 x 2] matrix, instead of the expected [425 x 1]. Why is this? How would you modify this code so I could see the individual values of each solution as I choose, and not just the last working portion? Since I am solving for two unknowns, I should be getting at least 850 solutions. I will omit the actual function when I present the code below, as it is quite long and it's contents are irrelevant to the discussion. The variables to be input are real numbers presented in single columns in a csv spreadsheet.
data = csvread('data.csv');
assert (mod(size(data, 1), 2) == 0, ...
'Input data must have an integer multiple of 2 rows');
assert (size(data, 2) == 7, ...
'Input data must have exactly seven columns.');
nsys = size(data, 1) / 2;
soln = zeros(nsys, 2);
options = optimset('MaxFunEvals', 1e10, 'MaxIter', 15000);
for k = 1 : nsys,
F = two_layer_nk_1d_gen(data(2*(k-1) + (1:2), 1:end));
Guess = [1,1];
soln(k, :) = fsolve(F, Guess, options);
fid = fopen('results_2layer_1d.csv','w');
fprintf(fid, '%5.5f\n', soln);
Function File:
function F = two_layer_nk_1d_gen(p)
assert(ndims(p) == 2, ...
'System parameters ''p'' must be 2D matrix.');
assert(all(size(p) == [2,7]), ...
'System parameters must be 2-by-7 matrix.');
y = p(:,1);
n0 = p(:,2);
n2 = p(:,3);
n3 = p(:,4);
k2 = p(:,5);
k3 = p(:,6);
R2 = p(:,7);
d1 = .34;
d2 = 300;
F = @(V) ...
I appreciate the help.
Andrew Newell
Andrew Newell on 8 Mar 2012
I don't see why you expect soln to have just one column. The code seems to produce an array with nsys x 2 elements.

Sign in to comment.

Answers (1)

Walter Roberson
Walter Roberson on 8 Mar 2012
Your Guess has two elements, so you are going to get two results per fsolve()
Your fprintf() is not correct for saving the solutions row-by-row. Use
fprintf(fid, '%5.5f,%5.5f\n', soln .' );
Note the .' transpose operation: it is needed in order to end up with row-by-row output.
  1 Comment
Alex on 9 Mar 2012
When I use that format (I have tried it) Matlab does not output the answers based on column, it outputs the answers sequentially such that, for solutions of A and B, [ A1, A2: A3, B1: B2, B3] which is not very helpful for data analysis.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!