Related
I am using the above code to generate COMTRADE files for different scenarios in the simulink.
but whenever I add a display into the simulation model i get an error saying the following
Caused by:
Dimensions of arrays being concatenated are not consistent.
How to resolve the issue so that i can use the display but at the same time, i want to create the COMTRADE file?
Following is the MATLAB code that i am using
% Create the .dat file
clc
format short
NS1 = size(tout); % to find the number of samples
NS2 = NS1(1,1);
FileName = input('Please enter a file name:', 's');
FN_cfg = [FileName,'.cfg'];
FN_dat = [FileName,'.dat'];
Data =[transpose((1:1:NS2)) tout M];
csvwrite(FN_dat,Data)
unique(tout, 'rows', 'stable');
% Create the .cfg file
Config = {'Simulation',' ' ,'1999' ;
'12', '12A', '0D'};
fileid = fopen(FN_cfg,'w');
for r = 1:size(Config,1)
for c = 1:size(Config,2)
var = eval(('Config{r,c}'));
if size(var,1) == 0
var = ' ';
end
if isnumeric(var) == 1
var = num2str(var);
end
fprintf(fileid,var);
if c ~= size(Config,2)
fprintf(fileid,(','));
end
end
fprintf(fileid, '\n');
end
fclose(fileid);
AC = {'1','Vr',' ',' ','V','1','0','0','-99999','99998','1','1','P';
'2','Vy',' ',' ','V','1','0','0','-99999','99998','1','1','P';
'3','Vb',' ',' ','V','1','0','0','-99999','99998','1','1','P';
'4','Ir',' ',' ','A','1','0','0','-99999','99998','1','1','P';
'5','Iy',' ',' ','A','1','0','0','-99999','99998','1','1','P';
'6','Ib',' ',' ','A','1','0','0','-99999','99998','1','1','P';
'7','Vr',' ',' ','V','1','0','0','-99999','99998','1','1','S';
'8','Vy',' ',' ','V','1','0','0','-99999','99998','1','1','S';
'9','Vb',' ',' ','V','1','0','0','-99999','99998','1','1','S';
'10','Ir',' ',' ','A','1','0','0','-99999','99998','1','1','S';
'11','Iy',' ',' ','A','1','0','0','-99999','99998','1','1','S';
'12','Ib',' ',' ','A','1','0','0','-99999','99998','1','1','S'};
fileid = fopen(FN_cfg,'a');
for r = 1:size(AC,1)
for c = 1:size(AC,2)
var = eval(('AC{r,c}'));
if size(var,1) == 0
var = ' ';
end
if isnumeric(var) == 1
var = num2str(var);
end
fprintf(fileid,(var));
if c ~= size(AC,2)
fprintf(fileid,(','));
end
end
fprintf(fileid, '\n');
end
fprintf(fileid, '50','\n');
fprintf(fileid, '\n1');
fprintf(fileid, '\n20000,');
fprintf(fileid, '%1d',(NS2));
fprintf(fileid, '\n%s', (datestr(now)));
fprintf(fileid, '\n%s', (datestr(now)));
fprintf(fileid, '\nASCII');
fprintf(fileid, '\n1');
fclose(fileid);
disp('COMTRADE GENERATED!')
I have a function that can plot multiple series on a plot, given a list of table headers wanted as series. I am unsure of how to account for a variable input in the one argument spot, where it accepts either a string, or cell array of strings, depending on how the series should be specifically broken down. For example, calling it as such
table2multiseries(myTable, 'Xvals', 'Yvals', 'name');
would plot x vs y where each series is for a different name, i.e. "John", "Rob", etc.
Or it can be called with a cell array for the series names, as follows:
table2multiseries(myTable, 'Xvals', 'Yvals', {'name', 'trial'});
This would plot x vs y where each series is for a different name and trial number, i.e. "John - 1", "John - 2", "Rob - 1", "Rob - 2", etc.
This is the code, where there is an if statement that accounts currently for sName being either 1, 2, or 3 strings. This is a hack job, no doubt, as it repeats itself about 3 times. I'm wondering how to have it simplified to handle any length of series name criteria inputs. Any ideas?
function figHandle = table2multiseries(tb, xName, yName, sName)
figHandle = figure;
hold on;
sList = unique(tb{:, sName}, 'rows');
if ischar(sName)
for k = 1:length(sList)
iRows = tb{:, sName}==sList(k,1);
leg{sList==s} = [sName ' ' num2str(s)];
tbtemp = tb(iRows, :);
tbtemp = sortrows(tbtemp, xName);
plot(tbtemp{:, xName}, tbtemp{:, yName}, '-o')
end
elseif iscellstr(sName) && length(sName)==2
for k = 1:length(sList)
iRows = tb{:, sName{1}}==sList(k,1) & tb{:, sName{2}}==sList(k,2)
leg{k,1} = [sName{1} ' ' num2str(sList(k,1)) ' - ' sName{2} ' ' num2str(sList(k,2)) ];
tbtemp = tb(iRows ,:);
tbtemp = sortrows(tbtemp, xName);
plot(tbtemp{:, xName}, tbtemp{:, yName}, '-o')
end
elseif iscellstr(sName) && length(sName)==3
for k = 1:length(sList)
iRows = tb{:, sName{1}}==sList(k,1) & tb{:, sName{2}}==sList(k,2) & tb{:, sName{3}}==sList(k,3);
leg{k,1} = [sName{1} ' ' num2str(sList(k,1)) ' - ' sName{2} ' ' num2str(sList(k,2)) ' - ' sName{3} ' ' num2str(sList(k,3)) ];
tbtemp = tb(iRows, :);
tbtemp = sortrows(tbtemp, xName);
plot(tbtemp{:, xName}, tbtemp{:, yName}, '-o')
end
end
title(tb.Properties.Description)
legend(leg);
end
I am making a black jack program for a class, and i have a series of "if loops"my issue is thatwhen i say yes, hit me with another card, it proceeds to the next step as i would like, but when i say "no, i am holding", it still asks me if i would like to hit again. How can i make it so that when i say no, I then end the function completly? program is below.
players=input('Welcome to Matjack! Aces count as 11, and face cards count as 10. Please enter the number of players:')
if players==1;
card_1=randi(11,1);
card_2=randi(11,1);
fprintf ('Face up card is %d! Face down is unknown!',card_1)
hit=input(' Hit? Y/N:','s')
if hit=='Y';
card_3=randi(11,1);
cards=card_1+card_3;
player_1=card_1+card_2+card_3;
if player_1<21;
fprintf('Value of face up cards is %d. Face down is still unknown!',cards);
hit=input(' Hit again? Y/N:','s')
if hit=='Y';
card_4=randi(11,1);
cards=card_1+card_3+card_4;
player_1=card_1+card_2+card_3+card_4;
end
if player_1>21 ;
fprintf ('Player one broke! Total card value was %d',player_1)
end
if hit=='N';
player_1=card_1+card_2+card_3;
fprintf ('Player one holds! Total card value was %d',player_1)
end
end
if player_1<21
fprintf('Value of face up cards is %d. Face down is still unknown!',cards);
hit=input(' Hit again? Y/N:','s')
if hit=='Y';
card_5=randi(11,1);
cards=card_1+card_3+card_4+card_5;
player_1=card_1+card_2+card_3+card_4+card_5;
end
if player_1>21 ;
fprintf ('Player one broke! Total card value was %d',player_1)
end
if hit=='N';
player_1=card_1+card_2+card_3+card_4;
fprintf ('Player one holds! Total card value was %d',player_1)
end
end
if player_1<21
fprintf('Value of face up cards is %d. Face down is still unknown!',cards);
hit=input(' Hit again? Y/N:','s')
if hit=='Y';
card_6=randi(11,1);
cards=card_1+card_3+card_4+card_5+card_6;
player_1=card_1+card_2+card_3+card_4+card_5+card_6;
end
if player_1>21 ;
fprintf ('Player one broke! Total card value was %d',player_1)
end
if hit=='N';
player_1=card_1+card_2+card_3+card_4+card_5;
fprintf ('Player one holds! Total card value was %d',player_1)
end
end
if player_1<21
fprintf('Value of face up cards is %d. Face down is still unknown!',cards);
hit=input(' Hit again? Y/N:','s')
if hit=='Y';
card_7=randi(11,1);
cards=card_1+card_3+card_4+card_5+card_6+card_7;
player_1=card_1+card_2+card_3+card_4+card_5+card_6+card_7;
end
if player_1>21 ;
fprintf ('Player one broke! Total card value was %d',player_1)
end
if hit=='N';
player_1=card_1+card_2+card_3+card_4+card_5+card_6;
fprintf ('Player one holds! Total card value was %d',player_1)
end
end
end
if hit=='N';
player_1=card_1+card_2;
fprintf ('Player one holds! Total card value was %d',player_1)
end
end
I worked on it a bit. Some functions you might want to add are the split, put in suits, and add in persistent player names. I tried to put in descriptive variable and function names.
function Matjack
global AllCards decks
AllCards = [];
clc
DealerHitOnSoft17 = 1;
disp('Welcome to Matjack! Aces count as 11, and face cards count as 10.')
if DealerHitOnSoft17
disp('Dealer hits on soft 17')
else
disp('Dealer holds on soft 17')
end
NumberPlayers = input('Please enter the number of players:');
decks = input('How many decks of cards do you want to play with? ');
playerName = cellfun(#(n) strjoin({'Player ', num2str(n)}, ' '), num2cell((1:NumberPlayers)'), 'uni', 0);
dealerCards = DealCards(2, []);
if Blackjack('Dealer', dealerCards)
printHand('Dealer''s', dealerCards)
disp('You lose')
return
end
printHand('Dealer''s', dealerCards(1))
playerHands = cellfun(#(n) DealCards(n, []), num2cell(2 * ones( NumberPlayers, 1)), 'uni', 0);
isPlaying = ones(size(playerHands));
for i = 1:NumberPlayers
isPlaying(i) = ~Blackjack(['Player ', num2str(i)], playerHands{i});
end
while any(isPlaying)
for i = 1:NumberPlayers
if isPlaying(i)
printHand(playerName{i}, playerHands{i})
if strcmpi(input([playerName{i}, ' has ', num2str(sumHand(playerHands{i}, 0)),'. Hit? Y/N:'],'s'), 'y')
playerHands{i} = DealCards(1, playerHands{i});
printHand(playerName{i}, playerHands{i})
disp([playerName{i}, ' has ', num2str(sumHand(playerHands{i}, 0)),'.'])
if sumHand(playerHands{i}, 0) > 21
disp([playerName{i}, ' busts!'])
isPlaying(i) = 0;
end
else
disp([playerName{i}, ' holds at ', num2str(sumHand(playerHands{i}, 0)),'.'])
isPlaying(i) = 0;
end
end
end
end
printHand('Dealer''s', dealerCards)
while sumHand(dealerCards, DealerHitOnSoft17) < 17
dealerCards = DealCards(1, dealerCards);
printHand('Dealer', dealerCards)
if sumHand(dealerCards, DealerHitOnSoft17) > 21
disp('Dealer busts!')
elseif sumHand(dealerCards, DealerHitOnSoft17) > 17
disp(['Dealer holds at ', num2str(sumHand(dealerCards, DealerHitOnSoft17)),'.'])
else
disp(['Dealer has ', num2str(sumHand(dealerCards, DealerHitOnSoft17)),'.'])
end
end
cellfun(#(name, h) WinDrawLose(name, sumHand(h, 0), sumHand(dealerCards, DealerHitOnSoft17)), playerName, playerHands);
end
function hand = DealCards(N, hand)
global AllCards decks
possibleCards = randi(52 * decks, N, 1);
[C, ia, ~] = unique([AllCards; possibleCards], 'stable');
ia = ia - length(AllCards);
ia(ia < 1) = [];
n = length(AllCards) + N - length(C);
AllCards = C;
hand = [hand; possibleCards(ia)];
if n > 0
hand = DealCards(n, hand);
end
end
function printHand(player, hand)
ord = horzcat('Ace', cellfun(#num2str, num2cell(2:10), 'uni', 0), 'Jack', 'Queen', 'King');
hand = mod(hand - 1, 13) + 1;
if length(hand) == 1
disp([player, ' face up card is ', strjoin(ord(hand), ', '), '. Face down is unknown!'])
elseif length(hand) > 1
disp([player, ' cards are ', strjoin(ord(hand), ', '), '.'])
end
end
function S = sumHand(hand, dealerSoft)
hand = mod(hand - 1, 13) + 1;
hand(hand >= 10) = 10;
hand(hand == 1 ) = 11;
S = sum(hand);
while ((S > 21) && any(hand == 11))
if ~(dealerSoft && ((17 <= S) && (S <= 21)))
n = find(hand == 11, 1, 'first');
hand(n) = 1;
S = sum(hand);
end
end
end
function bj = Blackjack(player, hand)
if (length(hand) == 2) && (sumHand(hand, 0) == 21)
bj = 1;
disp([player, ' hit blackjack!'])
else
bj = 0;
end
end
function WinDrawLose(name, player, dealer)
if ((player < dealer) && (dealer <= 21)) || (player > 21)
disp([name, ' loses.'])
elseif (player == dealer)
disp([name, ' draws.'])
else
disp([name, ' wins.'])
end
end
I am doing a basic MATLAB online-course and in one part of the last assignment I need to "create a line graph from an expression based on user input".
My interpretation is that a user should be able to type in an expression f(x)=... such as:
3x^2+3x+c
I have successfully written code that will ask the user for the number of variables (numbers before the x:s) and exponents and if there is an constant or not.
Also, my code then generates variables from user input (input: string -> genvarname), and then assigns a correct value to it also from user input via the eval command/function.
Lastly, I have done an for-loop and used exist to determine if a variable exists.
My question now is, how can I use the result from exist (eg = 1) in a if-loop to access the variable and store it in an vector.
That way I believe I can with another for loop calculate values for y. the x-values are just x = -50:1:50, but if there are any suggestions for how to calculate y simpler than please tell me.
I have gained lots of information from reading StackOverflow posts, I just hope my question is relevant, and helpful. :)
EDIT:
%% Initial questions
IN = input('Give foo: [på formen A1x^a1+A2x^a2...Nx^n+KONST] ','s');
if isempty(IN)
IN = '3x^2+4x+2';
end
disp(['Du vill plotta ' IN]);
vars_qty = input('Hur många variabler har du? ');
if isempty(vars_qty)
vars_qty = 2;
end
exps_qty = vars_qty;
const = input('Har du en konstant på slutet? [Ja/Nej] ','s');
if isempty(const)
const = 'Ja';
end
disp(' ');
%vars_vector_name = cell(vars_qty, 1); % cell array with variable names
vars_vector_vals = zeros(vars_qty, 1); % vector with variable values
%exps_vector_name = cell(exps_qty, 1); % cell array with exponent names
exps_vector_vals = zeros(exps_qty, 1); % vector with exponent values
%% Assigning vectors
x = -50:1:50; % x vector
A = zeros(vars_qty, 1);
a = zeros(vars_qty, 1);
%% Assigning variable and exponent names + create variables and set a value to it
for i = 1:vars_qty
disp(['Variabel ' num2str(i) ':']);
% vars_vector_name(i, 1) = cellstr(input('Var god och namnge variabeln [A1,B..] ', 's')); %
... does not like an empty input
var = input('Var god och namnge variabeln [A1,A2...An] ', 's');
% if isempty(var)
% var = ['A',num2str(i)];
% end
vars_vector_vals(i, 1) = input('Vad är värdet på variabeln? '); %
... does not like an empty input
% if isempty(vars_vector_vals(i, 1))
% vars_vector_vals(i, 1) = i;
% end
vars_gen = genvarname( var );
eval([ var '= vars_vector_vals(i, 1);' ]);
vars_exist = exist( ['A',num2str(i)], 'var'); % isvarname( num2str(vars_gen) ); % num2str(vars_gen)
if vars_exist == 1
disp('Exist!');
% A(i, 1) = vars_gen;
% A(i, 1) = eval([ var '= vars_vector_vals(i, 1);' ]);
else
...
end
disp(['Exponent ' num2str(i) ':']);
exps = input('Var god och namnge exponenten [a1,a2...an & a2<a1] ', 's');
% if isempty(exps)
% exp = ['a',num2str(i)];
% end
exps_vector_vals(i, 1) = input('Vad är värdet på exponenten? '); %
... does not like an empty input
% if isempty(exps_vector_vals(i, 1))
% exps_vector_vals(i, 1) = i;
% end
exps_gen = genvarname( exps );
eval([ exps '= exps_vector_vals(i, 1);' ]);
exps_exist = exist( ['a',num2str(i)], 'var'); % isvarname( num2str(exps_gen) ); % num2str(exps_gen)
if exps_exist == 1
disp('Exist!');
% a(i, 1) = exps_gen;
% a(i, 1) = eval([ exps '= exps_vector_vals(i, 1);' ]);
else
...
end
end
% exps_vector_name(j, 1) = cellstr(input('Var god och namnge exponenten [a,b.. & b<a] ', 's')); %
... does not like an empty input
if strcmp(const,'Ja')
disp(' ');
const_scalar = input('Vad är värdet på konstanten? '); % scalar with constant
else
const_scalar = 0;
end
%gen_vars = genvarname({ (vars_vector_name(:,1)) });
%gen_exps = genvarname({ (exps_vector_name(:,1)) });
%eval([ gen_vars '= vars_vector_vals(:,1);' ]); % doesn't like a cell array
%eval([ gen_exps '= exps_vector_vals(:,1);' ]); % doesn't like a cell array
y = zeros(vars_qty, 1);
% for k = 1:vars_qty
% y(k, 1) =
% end
MATLAB's EXIST command is a little tricky to use correctly because it checks so many things. Here's how I would write this:
userVarName = ...
if exist(userVarName, 'var') == 1 % Return value 1 indicates a variable.
varValue = eval(userVarName);
else
error('Variable "%s" does not exist.', userVarName);
end
EDIT
Looks like the relevant portion of your code needs to be adapted like so:
vars_name = ['A', num2str(j)];
if exist(vars_name, 'var') == 1
A(j, 1) = eval(vars_name);
end
I was wondering if I have any chance to create a logical schema(state diagram) in matlab for a script. Or if I could find any programs that would do that for me.
for something like this:
A=[];
n=input('Numarul de linii & coloane al matricei A: ');
for i = 1:n
for j = 1:n
str = ['Introduceti elementul de pe randul ' num2str(i) ', coloana ' num2str(j) ': '];
A(i,j) = input(str);
end
end
A
suma=0;
for i = 1:n
for j = 1:n
if (i+j)<=(n) && A(i,j)<0;
suma = suma + A(i,j);
end
end
end
suma